简体   繁体   English

如何在脚本执行期间更改类的 __eq__

[英]How change __eq__ of class during script execution

<!-- language: lang-py -->

class File:
    ### Сlass initialization
    def __init__(self, path, name, size, date):
        self.path = path
        self.name = name
        self.size = size
        self.date = date

    def __eq__(self, other):
        # if self.name == other.name and self.size == other.size and self.date == other.date:
        if self.name == other.name and self.size == other.size:
        # if self.size == other.size and self.date == other.date:
            return True**

How change ( eq ) of class during script execution?在脚本执行期间如何更改 ( eq ) 类?

    def __eq__(self, other):
        # if self.name == other.name and self.size == other.size and self.date == other.date:
        if self.name == other.name and self.size == other.size:
        # if self.size == other.size and self.date == other.date:
        return True

Different variants must be triggered when certain conditions occur特定条件发生时必须触发不同的变体

Well, this is certainly possible:嗯,这当然是可能的:

class Foo(object):
    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        return other.x == self.x

foo1 = Foo(1)
foo2 = Foo(2)

print (foo1 == foo2)

def new_eq(self, other):
    return other.x - 1 == self.x

Foo.__eq__ = new_eq

print (foo1 == foo2)

Explanation:解释:

__eq__ is an attribute of the class Foo , and it's a function bound to the class (a class method). __eq__是类Foo一个属性,它是一个绑定到类的函数(类方法)。 You can set the __eq__ attribute to a new function to replace it.您可以将__eq__属性设置为新函数以替换它。 Note that because this is modifying the class, all instances see a change, including foo1 and foo2 that are already instantiated.请注意,因为这是在修改类,所以所有实例都会发生变化,包括已经实例化的foo1foo2

All that said, this is a pretty sketchy practice, especially for something like __eq__ , so I want to say that this is probably not a good solution to your problem, but not knowing what that problem is, I'll just say that if I were to see this sort of thing in code, it would make me rather nervous.综上所述,这是一个非常粗略的实践,特别是对于__eq__东西,所以我想说这可能不是解决您问题的好方法,但不知道那个问题是什么,我只会说,如果我如果在代码中看到这种东西,我会很紧张。

Instead of swapping __eq__ out on the fly, why not use the conditions to determine which case to use when __eq__ is called?与其即时交换__eq__ ,为什么不使用条件来确定在调用__eq__时使用哪种情况?

class Foo:
    def __eq__(self, other):
        if (self._condition_1):
            return self._eq_condition_1(other)
        elif (self._condition_2):
            return self._eq_condition_2(other)
        else:
            return self._eq_condition_default(other)

    def _eq_condition_1(self, other):
        return True

    def _eq_condition_2(self, other):
        return False

    def _eq_condition_default(self, other):
        return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM