考慮下面的代碼:猴修補操作符重載表現不同在Python2 VS Python3
class Foo:
def __mul__(self,other):
return other/0
x = Foo()
x.__mul__ = lambda other:other*0.5
print(x.__mul__(5))
print(x*5)
在Python2(帶from future import print
),此輸出
2.5
2.5
在Python3,這個輸出
2.5
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-36322c94fe3a> in <module>()
5 x.__mul__ = lambda other:other*0.5
6 print(x.__mul__(5))
----> 7 print(x*5)
<ipython-input-1-36322c94fe3a> in __mul__(self, other)
1 class Foo:
2 def __mul__(self,other):
----> 3 return other/0
4 x = Foo()
5 x.__mul__ = lambda other:other*0.5
ZeroDivisionError: division by zero
我遇到這種情況時,當我試圖實現一種類型sup移植了一部分代數運算。例如,我需要修改懶惰的乘法函數:一些計算必須推遲到實例與另一個變量相乘。猴子補丁在Python 2中工作,但我注意到它在3中失敗。
爲什麼會發生這種情況? 有什麼辦法可以在Python3中獲得更靈活的運算符重載?