python内运算符也是通过调用对象的特殊方法实现的
c=a+b 是通过 c=a.add_(b) 来实现的
比如 p=Person() 是用 init
记住 什么都是对象 运算符都是方法
#测试+的重载
class Person:
def __init__(self,name):
self.name=name;
def __add__(self, other):
if isinstance(other,Person):
return "{0}--{1}".format(self.name,other.name)
else:
return "不是同类对象,不能相加"
def __mul__(self, other):
if isinstance(other,Person):
return self.name*other
else:
return "不是同类对象,不能相加"
p1=Person("高")
p2=Person("低")
x=p1+p2
print(x)
print(x*5)
运行结果
高--低
高--低高--低高--低高--低高--低