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

2024-05-03 22:46:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当某些情况发生时,必须触发不同的变体


Tags: andpathnamepyselftruelangsize
2条回答

与其动态地交换__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

当然,这是可能的:

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__这样的东西,所以我想说这可能不是一个很好的解决问题的方法,但是不知道问题是什么,我只想说如果我在代码中看到这类东西,会让我相当紧张

相关问题 更多 >