python - 猴子在 Python 中修补 __eq__

标签 python python-3.x

无法理解为什么我能够在类之外重新定义(猴子补丁)__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/

相关文章:

python - 根据列表中的元素对列表作为值的字典进行排序

python - 返回作为参数传递的相同值的模拟方法

python 3 : remove overlaps in table

python - 如何在可翻译字符串中包含不间断空格

Python计算文本文件中的逗号

python - 如何在 python 中编辑请求以添加 TLS 设置?

python - 如何将 panda DataFrame 中的特定范围的元素转换为 float ?

python - 在 Python3 的一行中输入所有数字的最快方法?

python-3.x - django allauth 中的 Django 排序字段

Python:如何将不同数据帧中具有相同名称的列彼此相邻放置?