命名元组的等值比较重载

13

有没有一种方法来重载Python中namedtuple的等号运算符__eq__(self, other)

我知道这在类中是可以实现的,只需要重新定义该方法,但是否可以对namedtuple使用,并且如何实现?

3个回答

19

我认为,考虑到namedtuple的公共API,如果没有覆盖重写是不可能做到的。最短的解决方案是:

class Person(namedtuple('Person', ['ssn', 'name'])):
    def __eq__(self, other):
        return self.ssn == other.ssn
>>> p1 = Person("123", "Ozgur")
>>> p2 = Person("123", "EVR")
>>> print p1 == p2
True

另一个选项是:

>>> Person = namedtuple('Person', ['ssn', 'name'])
>>> Person.__eq__ = lambda x, y: x.ssn == y.ssn

6

据我所知,您无法对__eq__进行修补,但是您可以对namedtuple进行子类化,并在其中按您喜欢的方式实现它。例如:

from collections import namedtuple

class Demo(namedtuple('Demo', 'foo')):

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

使用中:

>>> d1 = Demo(1)
>>> d2 = Demo(1)
>>> d1 is d2
False
>>> d1 == d2
True

5

通过typing模块中的新Namedtuple类,可以实现这一点。我使用Python 3.6可以成功运行,但此方法在之前的版本也可能有效。

例如:

from typing import NamedTuple

class A(NamedTuple):
    x:str
    y:str
    def __eq__(self,other):
        return self.x == other.x

print(A('a','b') == A('a','c'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接