Write custom mappings without inheriting from dict
from collections.abc import Mapping
# ------------------------------------------
# ----SUBCLASSING dict WILL NOT GIVE YOU----
# -----ACCESS TO ITS INTERNAL C METHODS-----
# ------------------------------------------
#
# class DrownsMap(dict):
#
# def __getitem__(self, key):
# if key == 'ghost':
# return 'Boo!'
# return super().__getitem__(key)
#
# def boo(self, key):
# if key == "Ghost":
# return 'Boo!'
# else:
# return None
class DrownsMap(Mapping):
def __init__(self, *args, **kwargs):
self._storage = dict(*args, **kwargs)
def __getitem__(self, key):
if key == 'ghost':
return 'Boo!'
return self._storage[key]
def __iter__(self):
return iter(self._storage)
def __len__(self):
return len(self._storage)
custom_mapping = DrownsMap(one=1, two=2, three=3)
print(custom_mapping['one'])
print(custom_mapping['two'])
print(custom_mapping['three'])
print(custom_mapping.get("ghost"))
print(custom_mapping['ghost'])