gpt4 book ai didi

python - namedtuple 的相等重载

转载 作者:太空狗 更新时间:2023-10-29 22:06:33 26 4
gpt4 key购买 nike

有没有办法为 python 中的 namedtuple 重载相等运算符 __eq__(self, other)

我知道这在类和重新定义方法中是可能的,但这对于 namedtuple 是否也可能,您将如何实现它?

最佳答案

我认为,考虑到 namedtuple 的公共(public) 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

关于python - namedtuple 的相等重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com