__add__,表示‘左加’,及两个类型相加,A中有__add__,A的实例+B的实例,则能够执行,反之报错。
>>> class A:
pass
>>> class B:
def __add__(self,obj):
print ('B.__add__')
return self.v+obj.v
>>> b=B()
>>> a=A()
>>> b.v=2
>>> a.v=3
>>> b+a
B.__add__
5
>>> a+b
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
a+b
TypeError: unsupported operand type(s) for +: 'A' and 'B'
以上__add__定义后,可以操作在左边的报错,而处理右边则需要__radd__
>>> class B:
def __radd__(self,a):
print ('B.__radd__')
return self.v+a.v
>>> a+b
B.__radd__
5
>>> b+a
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
b+a
TypeError: unsupported operand type(s) for +: 'B' and 'A'
而__iadd__(原位操作)是为处理+=操作符。