![](/img/trans.png)
[英]how to see the body of __add__() method in python. whenever we see + operator, __add__() is called
[英]How to get __add__ called
class C(object):
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, C):
return self.value + other.value
if isinstance(other, Number):
return self.value + other
raise Exception("error")
c = C(123)
print c + c
print c + 2
print 2 + c
顯然,前兩個print語句將起作用,而第三個print語句由於int而失敗。 add ()無法處理C類實例。
246
125
print 2 + c
TypeError: unsupported operand type(s) for +: 'int' and 'C'
有沒有辦法解決這個問題,所以2 + c會導致C. add ()被調用?
您還需要添加__radd__
來處理相反的情況:
def __radd__(self, other):
if isinstance(other, C):
return other.value + self.value
if isinstance(other, Number):
return other + self.value
return NotImplemented
並注意您不應提出例外情況; 返回NotImplemented
單例。 這樣, 另一個對象仍然可以嘗試為您的對象支持__add__
或__radd__
,並且也將有機會實現加法。
當您嘗試添加兩個類型a
和b
,Python首先嘗試調用a.__add__(b)
; 如果該調用返回NotImplemented
,則嘗試嘗試b.__radd__(a)
。
演示:
>>> from numbers import Number
>>> class C(object):
... def __init__(self, value):
... self.value = value
... def __add__(self, other):
... print '__add__ called'
... if isinstance(other, C):
... return self.value + other.value
... if isinstance(other, Number):
... return self.value + other
... return NotImplemented
... def __radd__(self, other):
... print '__radd__ called'
... if isinstance(other, C):
... return other.value + self.value
... if isinstance(other, Number):
... return other + self.value
... return NotImplemented
...
>>> c = C(123)
>>> c + c
__add__ called
246
>>> c + 2
__add__ called
125
>>> 2 .__add__(c)
NotImplemented
>>> 2 + c
__radd__ called
125
您需要在__radd__
上實現__radd__
。
def __radd__(self, other):
return self.value + other
這會自動調用,因為int類將引發NotImplemented
錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.