Classes 9/11 does the code look right?


#1

The instructions:

Create a class ElectricCar that inherits from Car . Give your new class an __init__() method of that includes a battery_type member variable in addition to the model, color and mpg.

Then, create an electric car named my_car with a "molten salt" battery_type . Supply values of your choice for the other three inputs (model, color and mpg).

I thought I should write the code the way the discuss link told us:

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 !

So my code looks like this:

class ElectricCar(Car):

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

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

self.battery_type = battery_type

my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")

The Codecademy code:

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

my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")

So is it better to write it the way I did it or the Codecademy way?


#2

yours, codecademy violates DRY. But i think codecademy choice this approach given super() hasn’t been taught yet


#3

Great :wink:

I see I see


#4

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