i had a class called CacheObject,and many class extend from it.
now i need to add something common on all classes from this class so i write this
class CacheObject(object):def __init__(self):self.updatedict = dict()
but the child class didn't obtain the updatedict attribute.i know calling super init function was optional in python,but is there an easy way to force all of them to add the init rather than walk all the classes and modify them one by one?
I was in a situation where I wanted classes to always call their base classes' constructor in order before they call their own. The following is Python3 code that should do what you want:
class meta(type):def __init__(cls,name,bases,dct):def auto__call__init__(self, *a, **kw):for base in cls.__bases__:base.__init__(self, *a, **kw)cls.__init__child_(self, *a, **kw)cls.__init__child_ = cls.__init__cls.__init__ = auto__call__init__class A(metaclass=meta):def __init__(self):print("Parent")class B(A):def __init__(self):print("Child")
To illustrate, it will behave as follows:
>>> B()
Parent
Child
<__main__.B object at 0x000001F8EF251F28>
>>> A()
Parent
<__main__.A object at 0x000001F8EF2BB2B0>