eskhool eskhool - 2 months ago 5x
Python Question

Dictionary in a child class to update the dictionary with same name defined in parent class instead of over-riding

I have existing classes which inherit from each other…they already have a attribute which is being overridden in subclasses . I want the dictionary attribute to be updated instead of overridden…code below …

class A:
d = {1:2}

class B(A):
d = {3:4}


print b.d[1]
print b.d[3]

Is this possible at all? Say using metaclasses in a way that I can't think of readily.


Found this based on some of the ideas around:

class B(A): _d = {}

def __init__(self):
    for parent_klass in inspect.getmro(self.__class__):
        _d.update(getattr(parent_klass, 'd', {}))
    self.d = _d