Why did we reference a superclass in this excercise?



The code works correctly I just don’t understand why we have to implement super(ElectricCar, self).__init__(model, color, mpg)

class Car(object):
  condition = "new"
  def __init__(self, model, color, mpg):
    self.model = model
    self.color = color
    self.mpg   = mpg
  def display_car(self):
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
  def drive_car(self):
    self.condition = "used"
class ElectricCar(Car):
  def __init__(self, model, color, mpg, battery_type):
    #Why are we encorporating a superclass? 
    super(ElectricCar, self).__init__(model, color, mpg)
    self.battery_type = battery_type
my_car = ElectricCar("Tesla", "blue", 120, "molten salt")

print my_car.condition
print my_car.condition


Hi @cats999,

We don’t necessarily have to use the super function in the __init__ method for ElectricCar, however, doing so does enable us to use our previous work from the __init__ method of the Car class to initialize the model, color, and mpg instance variables of the ElectricCar class. Here, it only saves us a little work, but it is a good technique to know for other situations where it may come in handy.


I think what you are doing here is (and please someone tell me if I’m wrong).

Your ElectricCar constructor is expecting the model, color, mpg and battery_type as parameters.
Instead of typing

self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type

For your ElectricCar constructor, you are calling the constructor from your super class (Car class) and you send the parameters that your ElectricCar class and parent(super) class (Car) have in common.

super(ElectricCar, self).__init__(model, color, mpg)

by doing so, the constructor of the super class will initialize the values for those attributes of the object.

Now, you only initialize inside your ElectricCar constructor, the value for the attribute battery_type, and you avoid writing repetitive lines.

self.battery_type = battery_type

Hope this helps!


Yes, excellent point, @darkaden90. We should reuse our previous work when we can, and this is a good place to do that.


Adding onto what @appyle said, by using super, we are reusing code.

It’s a good practice to when we want to reuse the logic for:

  • initializing the properties
  • running any initialization code that’s in the base class

Why? We want to eliminate repeating code over and over again. Why? Because we have to debug, support, and maintain that code.

A better practice then is to eliminate redundancy and reuse code when possible.


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