python __add__

class Try_int(int):
    def __add__(self, other):
        print(self,other)
        return int(self) + int(other)
a = Try_int(1)
b = Try_int(3)
print(a + b)

输出为:

1 3
4

可见a为self,b为other



我们也可以自己定义一个类

class Try_int(int):
    def __add__(self, other):
        print(self,other)
        return int(self) - int(other)
a = Try_int(1)
b = Try_int(3)
print(a + b)

上述代码就等同于:

class Try_int(int):
    def __sub__(self, other):
        print(self,other)
        return int(self) - int(other)
a = Try_int(1)
b = Try_int(3)
print(a - b)

我们定义的这个类就是来控制这个“-”,“+”是用来做什么的,就像上面明明是__add__函数,而我们却让他输出了self与other的差。
return后面很关键。为什么要加int呢?是为了避免陷入无限递归。如下:

class Try_int(int):
    def __add__(self, other):
        print(self,other)
        return self + other
a = Try_int(1)
b = Try_int(3)
print(a + b)

大家可以运行一下,

1 3
1 3
1 3
1 3
1 3
1 3
#此处省略好多个1,3
1 3
1 3
1 3
1 3
1 3
1 3
Traceback (most recent call last):
  File "C:/Users/top/PycharmProjects/untitled4/venv/a_5.py", line 7, in <module>
    print(a + b)
  File "C:/Users/top/PycharmProjects/untitled4/venv/a_5.py", line 4, in __add__
    return self + other
  File "C:/Users/top/PycharmProjects/untitled4/venv/a_5.py", line 4, in __add__
    return self + other
  File "C:/Users/top/PycharmProjects/untitled4/venv/a_5.py", line 4, in __add__
    return self + other
  [Previous line repeated 992 more times]
  File "C:/Users/top/PycharmProjects/untitled4/venv/a_5.py", line 3, in __add__
    print(self,other)
RecursionError: maximum recursion depth exceeded while calling a Python object

return self + other就是返回对象本身加另外一个对象,再次调用__add__,陷入无限递归。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值