在Python类中支持等价(“相等”)的优雅方法

在Python类中支持等价(“相等”)的优雅方法

在编写自定义类时,通过==!=运算符允许等效通常很重要。在Python中,这可以通过分别实现__eq____ne__特殊方法来实现。我发现这样做的最简单方法是以下方法:

class Foo:
    def __init__(self, item):
        self.item = item    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

你知道更优雅的做法吗?您是否知道使用上述比较方法的任何特殊缺点__dict__

注意:有点澄清 - 何时__eq____ne__未定义,您会发现此行为:

>>> a = Foo(1)>>> b = Foo(1)>>> a is bFalse>>> a == bFalse

也就是说,a == b评估是False因为它真的运行a is b,是对身份的测试(即“ a与...相同的对象b”)。

__eq____ne__定义,你会发现这种行为(这是一个我们后):

>>> a = Foo(1)>>> b = Foo(1)>>> a is bFalse>>> a == bTrue


喵喵时光机
浏览 851回答 3
3回答

Qyouu

你需要小心继承:>>> class Foo:     def __eq__(self, other):         if isinstance(other, self.__class__):             return self.__dict__ == other.__dict__        else:             return False>>> class Bar(Foo):pass>>> b = Bar()>>> f = Foo()>>> f == bTrue>>> b == fFalse更严格地检查类型,如下所示:def __eq__(self, other):     if type(other) is type(self):         return self.__dict__ == other.__dict__    return False除此之外,您的方法将正常工作,这就是特殊方法。

慕标5832272

你描述的方式是我一直以来的方式。由于它完全是通用的,因此您可以始终将该功能分解为mixin类,并在需要该功能的类中继承它。class CommonEqualityMixin(object):     def __eq__(self, other):         return (isinstance(other, self.__class__)             and self.__dict__ == other.__dict__)     def __ne__(self, other):         return not self.__eq__(other)class Foo(CommonEqualityMixin):     def __init__(self, item):         self.item = item
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python