eskhool eskhool - 3 months ago 7
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}


b=B()

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


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

Answer

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', {}))
    _d.update(self.d)
    self.d = _d
Comments