9.Inheritance


#1

you have to reinitialize all member variables as you are modifying child class member function.
you can not use member function of Car class in child if you have same function in child class ...

here is the code<>

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
        
    def display_car(self):
        return "This is a %s %s with %s MPG." %(self.color, self.model, str(self.mpg))
    
    def drive_car(self):
        self.condition = "used"


my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition 

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("jaguar","red",52, "molten salt")

#2

Hi @viveknitd,

You can use a member method of the Car class in the child ElectricCar class even if you have the same method in that child class.

One strategy is to use the super function ...

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

Another technique is to call the method directly from the Car object ...

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

EDITED (January 26, 2017) based on @stetim94`s comment here: https://discuss.codecademy.com/t/9-inheritance/73719/3?u=appylpye


#3

new shouldn't be part of Car.init()?


#4

Oops, you are correct, @stetim94 . (I had experimented with a new version of the Car and ElectricCar classes and copied the experimental code to the post; have since edited the post to correct it.)


#5

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