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__,陷入无限递归。