I try to inherit a dict class, by implementing some logic during the initialization. To do so I add some of the key-value pairs in __init()__ method.
However, after initialization, the instance of my child class is always empty.
import copy
class my_dict(dict):
def __init__(self, raw_dict):
self = copy.deepcopy(raw_dict)
self['bar'] = raw_dict['foo']
original = {'foo' : 'apple'}
alfa = my_dict(original)
print(alfa)
prints empty dict while the expectation would be
[{'foo': 'apple', 'bar': 'apple'}]
How can I achieve the desired behaviour?
>Solution :
You can use the super constructor to do the effect you are looking for:
import copy
class my_dict(dict):
def __init__(self, raw_dict):
super().__init__(copy.deepcopy(raw_dict))
self['bar'] = raw_dict['foo']