【发布时间】:2010-07-11 13:37:05
【问题描述】:
假设我有一个这样的namedtuple:
FooTuple = namedtuple("FooTuple", "item1, item2")
我希望以下函数用于散列:
foo_hash(self):
return hash(self.item1) * (self.item2)
我想要这个,因为我希望 item1 和 item2 的顺序无关紧要(我将对比较运算符执行相同的操作)。我想到了两种方法来做到这一点。第一个是:
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
那么,我该怎么办?或者这完全是个坏主意,我应该从头开始编写自己的课程?
【问题讨论】:
标签: python inheritance overriding tuples