算數運算子過載:__add__ 、 __radd__ 、 __iadd__為例
__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