Class inheritance - Is this really the solution?


#1

I think I need some help on the excercise of Class inheritance: https://www.codecademy.com/courses/python-intermediate-en-egNXj/1/3?curriculum_id=4f89dab3d788890003000096#

When I "Save and submit code" it says "Way to go", but somehow it does not feel right. In my lines 19 -24 I wrote:

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

I thought that these lines should not be there, since they are already in the parentclass "Car". What is the use of inheritance when we copy the lines that are already there with the parents to the children?

Or am I making this too difficult? And is this simply the solution?:sunglasses:

Thanks for your help!

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, self.mpg)
    def print_car(self):
        print self.condition
        print self.model
        print self.color
        print self.mpg
    
    def drive_car(self):
        self.condition="used"

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("Stratingh", "silver", 20, "molten salt")

#2

At this point it is right. The ElectricCar instance variables override the Car class variables since it has its own __init__ method. In the next lesson you will learn about the super keyword where we pass the overridden properties up to the super class for initialization.


#3

Thank you, Roy; for answering and your very quick reply!!


#4

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