Why do I have to re-define all of my instance variables in ElectricCar’s __init__?


#1

Question

Why do I have to re-define all of my instance variables in ElectricCar’s init?

Answer

If we override a method, then the new method must be defined in such a way that it does everything you want it to do, which may include everything from the original method! If that’s the case, we’ve learned about calling the parent method by using the super keyword, so that’ll save us some time.
We can just call the parent Car __init__() method by using the super keyword that we learned about earlier, and then add whatever we like afterwards, like this:

def __init__(self, model, color, mpg, battery_type):
    super(ElectricCar, self).__init__(model, color, mpg)
    # Add code to define battery_type instance variable here!

That saves us the trouble of rewriting those lines of code we already wrote, while allowing us to add more to the end for our battery_type!


FAQ: Learn Python - Classes - Inheritance