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

时间:2018-02-08 22:01:50

标签: python python-3.x

<!-- 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**

脚本执行期间如何更改( 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

发生特定情况时必须触发不同的变种

2 个答案:

答案 0 :(得分:1)

嗯,这当然是可能的:

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)

说明:

__eq__是类Foo的属性,它是绑定到类的函数(类方法)。您可以将__eq__属性设置为新函数以替换它。请注意,因为这是修改类,所有实例都会看到一个更改,包括已经实例化的foo1foo2

所有这一切,这是一个非常粗略的做法,特别是像__eq__之类的东西,所以我想说这可能不是你的问题的一个很好的解决方案,但不知道那个问题是什么,我我只想说如果我在代码中看到这种东西,那会让我很紧张。

答案 1 :(得分:0)

不是动态地交换__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