版权声明:转载 或者复制请标注来源 https://blog.csdn.net/qq_34979346/article/details/83120345
通过一个代码段理解下,如下:
class Model:
def __init__(self,x):
self.x=x
def __add__(self, other):
return Model(self.x+other.x)
def __str__(self):
return ("两个对象相加的值是{x}".format(x=self.x))
a=Model(5)
b=Model(7)
print(a+b)
看到了 add 函数接受两个参数 都是对象,所以要系统识别是两个对象相加才能进行调用这个函数, 我return 也是对象,这样就可以 当print 的时候 调用 我自定义的str 方法。