我一直在使用overload numeric operators通過object.__add__(self,other)
等類特殊方法.檢索在實例上調用的二元運算符
是否有通用方法來找出哪個二進制運算符被調用了?
對於一元運算符,您可以使用__getattr__
,例如:
class Test():
def __getattr__(self, name):
print name
t = Test()
~t # prints __invert__
但是調用二元運算符,例如t+t
或t+5
總是調用__coerce__
,它會丟失有關運算符的信息。
解決方案基於Jochen Ritzel的答案如下:最簡單的方法是將以下內容添加到上面的類:
def __coerce__(self, other):
self.other = other # store 'other' somewhere we can access it
return None
然後__getattr__
(在__coerce__
之後調用)可以訪問兩個操作數 - 如self
和self.other
- 以及操作 - 如name
。
然而事實證明,嘗試通過__getattr__
使用動態調度幾乎可以肯定是真的是糟糕的想法與僅僅定義你真正需要的特殊方法相比,對於運算符(而不是屬性)Python實際上會調用任何__getattr__
回報。
(希望更新我的問題還可以,似乎不適合評論框)