set() 中可以使用命名元组吗?
Can namedtuples be used in set()?
我知道 namedtuple
是一个工厂函数,用于创建具有不可变数据字段的 类。我假设它们是可散列的,以便它们可以成套使用。我担心的是是否存在与在集合中使用命名元组相关的陷阱。例如如果嵌套 namedtuple
s 会有问题吗?
是的,它们是可散列的,并且可以在集合中使用,例如 tuples
。
问题是可变对象的元组可以在你下面改变。
由不可变对象组成的元组在这方面是安全的。
不确定这是不是陷阱,但值得注意@user2357112supportsMonica 在评论中的评论:
The other gotcha is that a namedtuple is still a tuple, and its
__hash__
and __eq__
are ordinary tuple hash and equality. A namedtuple
will compare equal to ordinary tuples
or instances of unrelated
namedtuple
classes if the contents match.
我知道 namedtuple
是一个工厂函数,用于创建具有不可变数据字段的 类。我假设它们是可散列的,以便它们可以成套使用。我担心的是是否存在与在集合中使用命名元组相关的陷阱。例如如果嵌套 namedtuple
s 会有问题吗?
是的,它们是可散列的,并且可以在集合中使用,例如 tuples
。
问题是可变对象的元组可以在你下面改变。
由不可变对象组成的元组在这方面是安全的。
不确定这是不是陷阱,但值得注意@user2357112supportsMonica 在评论中的评论:
The other gotcha is that a namedtuple is still a tuple, and its
__hash__
and__eq__
are ordinary tuple hash and equality. Anamedtuple
will compare equal to ordinarytuples
or instances of unrelatednamedtuple
classes if the contents match.