gpt4 book ai didi

python - 子类化时不可散列的类型 `int`

转载 作者:行者123 更新时间:2023-11-30 23:02:42 25 4
gpt4 key购买 nike

让我们定义一个非常简单的Test类,它继承自int:

TEST_DICT = {1: 'a', 2: 'b'}


class Test(int):

def __str__(self):
return TEST_DICT[self]

def __repr__(self):
return str(self)


if __name__ == '__main__':
print(Test(1))

这将打印 a,正如预期的那样,它是此 Test 类的 1 的表示形式。

现在,让我们重新定义 __eq__ 方法:

TEST_DICT = {1: 'a', 2: 'b'}


class Test(int):

def __str__(self):
return TEST_DICT[self]

def __repr__(self):
return str(self)

def __eq__(self, other):
if isinstance(other, int):
return self == other
if isinstance(other, str):
return str(self) == other
return False


if __name__ == '__main__':
print(Test(1))

但是,这会导致以下回溯:

Traceback (most recent call last):
File "test.py", line 14, in <module>
print(Test(1))
File "test.py", line 4, in __str__
return TEST_DICT[self]
TypeError: unhashable type: 'Test'

有人可以解释为什么会发生这种情况以及如何避免此错误,同时仍然能够重新定义 __eq__ 方法吗?

最佳答案

来自https://docs.python.org/2/reference/datamodel.html :

here are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining eq(), one should also define ne() so that the operators will behave as expected. See the paragraph on hash() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys.

还有

If a class does not define a cmp() or eq() method it should not define a hash() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable in hashed collections. If a class defines mutable objects and implements a cmp() or eq() method, it should not implement hash(), since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

User-defined classes have cmp() and hash() methods by default; with them, all objects compare unequal (except with themselves) and x.hash() returns a result derived from id(x).

关于python - 子类化时不可散列的类型 `int`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34394546/

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