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 keys need to be hashable, which requires implementing __hash__
method.
By default, objects implement id-based hash function. Hash has little meaning for mutable objects though, so it is removed from implementation of built-in classes of such types. You can do the same with custom classes by assigning None to the method:
class MyClassA:
def __init__(self, value=0):
self.value = value
__hash__ = None
dict_[MyClassA()] = 1 # TypeError: unhashable type: 'MyClassA'
As to question 1 - no, you can change values of A.value
and B.value
and B.list
so they are not immutable.
Side notes:
self.list
.