无法理解为什么我能够在类之外重新定义(猴子补丁)__eq__
,但不能通过 __init__
或在类中更改其定义方法:
class SpecialInteger:
def __init__(self,x):
self.x = x
self.__eq__ = self.equals_normal
def equals_normal(self,other):
return self.x == other.x
def equals_special(self,other):
return self.x != other.x
def switch_to_normal(self):
self.__eq__ = self.equals_normal
def switch_to_special(self):
self.__eq__ = self.equals_special
a = SpecialInteger(3)
b = SpecialInteger(3)
print(a == b) # false
a.switch_to_normal()
print(a == b) # false
SpecialInteger.__eq__ = SpecialInteger.equals_normal
print(a == b) # true
SpecialInteger.__eq__ = SpecialInteger.equals_special
print(a == b) # false
我只是错误地使用了 self
还是有其他原因导致它这样工作?
最佳答案
要在类中执行此操作,您只需在类中定义 __eq__
方法即可。
class SpecialInteger:
def __init__(self,x):
self.x = x
def __eq__(self, other):
# do stuff, call whatever other methods you want
编辑:我明白你在问什么,你希望在实例级别覆盖该方法(这是一个“魔术”方法)。我不相信这在语言的基本结构中是可能的,per this discussion .
你的猴子补丁在那个例子中起作用的原因是因为它是在类级别传递的,而不是实例级别,而 self
指的是实例。
关于python - 猴子在 Python 中修补 __eq__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878846/