Use identity-based equality and hashing, while keeping mutable contents in an attribute. Changing the contents then does not change the dictionary key's identity.
Изменяемая коллекция, которая может выступать в качестве ключа словаря
Use identity-based equality and hashing, while keeping mutable contents in an attribute. Changing the contents then does not change the dictionary key's identity.
Короткий ответ
Что ответить на собеседовании
Подробный разбор
Ответ с пояснениями
Условие
Create a mutable container (for instance, a list‑like structure) whose objects are eligible to be used as keys in a Python dict.
# TODO: создать собственный класс, экземпляры которого можно использовать как ключи
Ответ
Use identity-based equality and hashing, while keeping mutable contents in an attribute. Changing the contents then does not change the dictionary key's identity.
class MutableContainer:
def __init__(self, items=()):
self.items = list(items)
def append(self, value):
self.items.append(value)
def __iter__(self):
return iter(self.items)
def __getitem__(self, index):
return self.items[index]
key = MutableContainer([1])
lookup = {key: 'value'}
key.append(2)
assert lookup[key] == 'value'
The class inherits object equality and hashing, so two containers with equal contents remain distinct keys. Do not calculate a hash from mutable contents: modifying them could make an existing dictionary entry unreachable. Value-based keys should instead use an immutable snapshot, such as a tuple.