无法理解为什么我能够重新定义(猴子补丁)__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
编辑:我明白你在问什么,你希望在实例级别覆盖该方法(这是一个“魔术”方法)。我不相信这在语言的基本结构中是可能的,根据本次讨论 https://stackoverflow.com/questions/10376604/overriding-special-methods-on-an-instance.
您的猴子补丁在该示例中起作用的原因是因为它是在类级别传递的,而不是在实例级别上传递,而self
指的是实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)