How to call Base Class's __init__ method from the child class? [duplicate] How to call Base Class's __init__ method from the child class? [duplicate] python python

How to call Base Class's __init__ method from the child class? [duplicate]


You could use super(ChildClass, self).__init__()

class BaseClass(object):    def __init__(self, *args, **kwargs):        passclass ChildClass(BaseClass):    def __init__(self, *args, **kwargs):        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):    condition = "new"    def __init__(self, model, color, mpg):        self.model = model        self.color = color        self.mpg   = mpgclass ElectricCar(Car):    def __init__(self, battery_type, model, color, mpg):        self.battery_type=battery_type        super(ElectricCar, self).__init__(model, color, mpg)car = ElectricCar('battery', 'ford', 'golden', 10)print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}


As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super() since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__ instead. Here is the code after incorporating these changes :

class Car(object):    condition = "new"    def __init__(self, model, color, mpg):        self.model = model        self.color = color        self.mpg   = mpgclass ElectricCar(Car):    def __init__(self, battery_type, model, color, mpg):        self.battery_type=battery_type        super().__init__(model, color, mpg)

Thanks to Erwin Mayer for pointing out the issue in using __class__ with super()


If you are using Python 3, it is recommended to simply call super() without any argument:

class Car(object):    condition = "new"    def __init__(self, model, color, mpg):        self.model = model        self.color = color        self.mpg   = mpgclass ElectricCar(Car):    def __init__(self, battery_type, model, color, mpg):        self.battery_type=battery_type        super().__init__(model, color, mpg)car = ElectricCar('battery', 'ford', 'golden', 10)print car.__dict__

Do not call super with class as it may lead to infinite recursion exceptions as per this answer.