定义加号的操作,即当使用+操作时,将会触发__add__()
方法
我们先看实例对象相加的情况:
class MyStr():
def __init__(self,value):
self.value = value
def __str__(self):
return self.value
s1=MyStr('aaa')
s2=MyStr('BBBB')
print(s1)
print(s2)
print(s1+s2)
运行结果:
aaa
BBBB
Traceback (most recent call last):
File "C:/workspace/pythonTest/pythonDemo/add.py", line 12, in <module>
print(s1+s2)
TypeError: unsupported operand type(s) for +: 'MyStr' and 'MyStr'
发现会报错也就是两个实例对象无法直接相加
加入魔法方法__add__
后再来看看: