# 特殊方法重载
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
def __add__(self, other):
if isinstance(other, Person):
return "{0} -- {1}".format(self.name, other.name)
else:
return "不是同类对象不能相加P"
class Chinese(Person):
def __init__(self, name, age, festival):
Person.__init__(self, name, age)
self.festival = festival
def __add__(self, other):
if isinstance(other, Chinese):
return "{0} ++ {1}".format(self.festival, other.festival)
else:
return "不是同类对象不能相加C"
def __mul__(self, other):
if isinstance(other, int):
return self._Person__age * other
p1 = Person("seeleP", 12)
p2 = Chinese("seeleC", 12, "Mid-Autumn Festival")
p3 = Chinese("annie", 12, "Spring Festival")
x = p1 + p2
y = p2 + p3
z = p2*3
print(x)
print(y)
print(z)

如果把 x = p1 + p2 改为 x = p2 + p1, 结果就会不一样
x = p2 + p1

麻烦老师解释一下为什么顺序不同产生的结果也不同,谢谢