Python的运算符实际上是通过调用对象的特殊方法实现的。比如:
a = 20
b = 30
c = a + b
print(c)
d = a.__add__(b)
print(d)
执行结果
部分运算符如下
需要时可以重写以上的方法
使用方法如下(以__add__()为例):
# 运算符重载
class Animal:
def __init__(self, name):
self.name = name
def shout(self):
print("动物在叫~")
def __add__(self, other):
if isinstance(other, Animal):
self.name += other.name
return self
else:
print("不是同类对象,不能相加")
a1 = Animal("dog")
a2 = Animal("cat")
x = a1 + a2
print(x.name)
print(type(x))
输出结果