class MyClassA:
def __init__(self, value=0):
self.value = value
class MyClassB:
def __init__(self, value=0, list_=[]):
self.value = value
self.list = list_
a = MyClassA()
b = MyClassB()
c = []
dict_ = {}
dict_[a] = 1 # No error
dict_[b] = 1 # No error
dict_[c] = 1 # TypeError: unhashable type: 'list'
dict 键需要是 hashable,这需要实现
__hash__
方法。
默认情况下,对象实现基于 id 的哈希函数。不过,哈希对于可变对象没有什么意义,因此它从该类型的内置类的实现中删除。您可以通过将 None 分配给方法来对自定义类执行相同的操作:
class MyClassA:
def __init__(self, value=0):
self.value = value
__hash__ = None
dict_[MyClassA()] = 1 # TypeError: unhashable type: 'MyClassA'
关于问题 1 - 不,您可以更改
A.value
和 B.value
和 B.list
的值,因此它们不是一成不变的。
旁注:
self.list
。