As you've already found the answer, you know you could use super(ChildClass, self).__init__()
. I would like to explain how it works using a simple example. In the below piece of code, I have called __init__
of BaseClass in the __init__
of ChildClass.
class BaseClass(object):
def __init__(self, *args, **kwargs):
pass
class ChildClass(BaseClass):
def __init__(self, *args, **kwargs):
#Calling __init__ of BaseClass
super(ChildClass, self).__init__(*args, **kwargs)
For example:
#Here is simple a Car class
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
#Inherit the BaseClass here
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
#calling the __init__ of class "Car"
super(ElectricCar, self).__init__(model, color, mpg)
#Instantiating object of ChildClass
car = ElectricCar('battery', 'ford', 'golden', 10)
print(car.__dict__)
Here's the output:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
Here is the link to the question from which my explanation is inspired. Hope it helps someone understand the concept better :)