Inheritance - Parent to sub


I am a bit confused with inheritance.

Say the parent has the following variables:

def __init__(self, model, color, mpg):

And the child class has an additional variable, say for e.g. battery_type

My question is,

Do we need to redeclare the variables of the parent class when we declare the sub class? As in

def __init__(self,model,color,mpg,Battery_type)

If we have to do the above, then why is that??

Or do we just declare the variables specific to the sub?



if it where only that simply, unfortunately that is not the case.

lets break it down. __init__() is a method, to be more specific, it is a magic method. (magic methods are special), so what is so special about __init__()? it is called when we create an instance of your class, so when we do this:

my_car = EletricCar("Rama", "red", 99, "molten salt")

__init__() is automatically called (init of electric car, not of car)

inheritance gives us access to parents methods, we can prove this by doing:


we could use this to our advantage, in our object we can use super() to call parent methods, so then we can do:

class EletricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super(EletricCar, self).__init__(model,color,mpg)
        self.battery_type = battery_type

this is already a lot better then the method suggested by the lesson.

Inheritance is complicated, we have access to parent methods, but this doesn't mean parents (magic) methods are automatically called.


Thank you stetim94... Very informative reply... My understanding from your reply is that this is determined on a case by case basis... Is this correct??


what does this refers to?

i am afraid i don't understand what you mean, could you elaborate?


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.