gpt4 book ai didi

python - 使用自定义哈希函数创建命名元组

转载 作者:IT老高 更新时间:2023-10-28 20:53:49 25 4
gpt4 key购买 nike

假设我有一个像这样的 namedtuple:

FooTuple = namedtuple("FooTuple", "item1, item2")

我希望以下函数用于散列:

foo_hash(self):
return hash(self.item1) * (self.item2)

我想要这个,因为我希望 item1item2 的顺序无关紧要(我将对比较运算符执行相同的操作)。我想到了两种方法来做到这一点。第一个是:

FooTuple.__hash__ = foo_hash

这可行,但感觉被黑了。所以我尝试子类化 FooTuple:

class EnhancedFooTuple(FooTuple):
def __init__(self, item1, item2):
FooTuple.__init__(self, item1, item2)

# custom hash function here

但后来我明白了:

DeprecationWarning: object.__init__() takes no parameters

那么,我该怎么办?或者这完全是个坏主意,我应该从头开始编写自己的类(class)?

最佳答案

我认为你的代码有问题(我的猜测是你创建了一个同名的元组实例,所以 fooTuple 现在是一个元组,而不是一个元组类),因为像这样子类化命名元组应该可以。无论如何,您不需要重新定义构造函数。您可以添加哈希函数:

In [1]: from collections import namedtuple

In [2]: Foo = namedtuple('Foo', ['item1', 'item2'], verbose=False)

In [3]: class ExtendedFoo(Foo):
...: def __hash__(self):
...: return hash(self.item1) * hash(self.item2)
...:

In [4]: foo = ExtendedFoo(1, 2)

In [5]: hash(foo)
Out[5]: 2

关于python - 使用自定义哈希函数创建命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223236/

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