__add__表示‘左加’,若对象在+右边则会报错TypeError
class Number:
def __init__(self, num):
self.num = num
def __str__(self):
return str(self.num)
# 对象出现在'+'的左边时自动触发
def __add__(self, other):
print('__add__')
return self.num + other
__radd__表示‘右加’,若对象在+左边会报错
class Number:
def __init__(self, num):
self.num = num
def __str__(self):
return str(self.num)
# 对象出现在'+'的左边时自动触发
def __radd__(self, other):
print('__radd__')
return self.num + other
__iadd__表示‘+=’
class Number:
def __init__(self, num):
self.num = num
def __str__(self):
return str(self.num)
# 对象出现在'+'的左边时自动触发
def __add__(self, other):
print('__iadd__')
return self.num + other