Python: Inherit the superclass __init__ Python: Inherit the superclass __init__ python python

Python: Inherit the superclass __init__


super(SubClass, self).__init__(...)

Consider using *args and **kw if it helps solving your variable nightmare.


You have to write it explicitly, but on the other hand, if you have lots of args, you should probably use *args for positional args and **kwargs for keyword args.

class SubClass(BaseClass):    def __init__(self, *args, **kwargs):        super(SubClass, self).__init__(*args, **kwargs)        # SubClass initialization code

Another technique you could use is to minimize the code in init and then at the end of init function, call another custom function. Then in the subclass, you just need to override the custom function

class BaseClass(object):    def __init__(self, *args, **kwargs):        # initialization code        self._a = kwargs.get('a')        ...        # custom code for subclass to override        self.load()    def load():        passclass SubClass(BaseClass)    def load():        # SubClass initialization code        ...


If the derived classes don't implement anything beyond what the base class __init__() already does, just omit the derived classes __init__() methods - the base class __init__() is then called automatically.

If, OTOH, your derived classes add some extra work in their __init__(), and you don't want them to explicitly call their base class __init__(), you can do this:

class BaseClass(object):    def __new__(cls, a, b, c, d, e, f, ...):        new = object.__new__(cls)        new._a=a+b        new._b=b if b else a        ...        return newclass A(BaseClass):    ''' no __init__() at all here '''class B(BaseClass):    def __init__(self, a, b, c, d, e, f, ...):        ''' do stuff with init params specific to B objects '''

Since __new__() is always called automatically, no further work is required in the derived classes.