如何理解Python中一切皆对象?

一、示例代码

  • 有理数类
import math

class rational:
    def __init__(self,p,q):
    	if q == 0:
    		raise ZeroDivisionError('denominator is zero')
        self.p = p
        self.q = q

    def __str__(self):
        return "{} / {}".format(self.p,self.q)

    def simplify(self):
        gcd = math.gcd(self.p,self.q)
        return rational(int(self.p / gcd),int(self.q / gcd))

    #加
    def __add__(self, other):
        return rational(self.p + other.p,self.q + other.q)
        
    #减
    def __sub__(self, other):
        return rational(self.p * other.q - other.p * self.q,self.q * other.q)
        
    #乘
    def __mul__(self, other):
        return rational(self.p * other.p,self.q * other.q)
        
    #除
    def __div__(self, other):
        return rational(self.p * other.q,self.q * other.p)
        
    #相等
    def __eq__(self, other):
        fz = self.simplify()
        fm = other.simplify()
        return fz.p == fm.p and fz.q == fm.q

    def __float__(self):
        return float(self.p / self.q)

Python中一切皆对象,如常见的加(+)、减(-)、乘(*)、除(/)、相等(==)都是调用类中的某个方法
eg:

self:指的是调用该函数的对象,指代的是对象本身,和Java中的this相同
r = rational(1,2)
r1 = rational(1,4)
r + r1表示r对象调用+方法,也就是__add__方法,传入r1对象作为参数,可以理解为
r.+(r1)
同理减、乘、除都是

二、Python中的魔法方法

__xx __()的函数叫做魔法方法,指的是具有特殊功能的函数
1、__init __()

  • 构造方法,在实例化对象时默认被调用,不需要手动调用

2、__str __()

  • 当使用print输出对象的时候,默认打印对象的内存地址。如果类定义了__str
    __方法,那么就会打印从在这个方法中return的数据,相当于Java中重写toString()方法

3、__repr __()

  • 和__str __作用一样,也是返回对象的字符串表示,区别是__str __目的是为了提供可读性好的输出,__repr __返回更官方一些,为了提供准确且详细的输出

eg:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f'Point({self.x}, {self.y})'

    def __repr__(self):
        return f'Point(x={self.x}, y={self.y})'

point = Point(2, 3)

print(str(point))  # 输出: Point(2, 3)
print(repr(point))  # 输出: Point(x=2, y=3)

4、__del __()
当删除对象时,python解释器也会默认调用__del __()方法

del 对象
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱夜来香A

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值