Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make child class call parent class __init__ automatically?

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?

like image 862
user2003548 Avatar asked Dec 06 '22 05:12

user2003548


1 Answers

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>
like image 129
james Avatar answered May 13 '23 16:05

james