9.Inheritance


#1



https://www.codecademy.com/courses/python-intermediate-en-egNXj/1/3?curriculum_id=4f89dab3d788890003000096


Oops, try again. my_car does not have a model member variable.


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, 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.battery_type = battery_type

my_car = ElectricCar("Audi Q4", "black", 90, "molten salt")


#2

here:

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

because you overwrite init of parent Car class you have re-initialize all instance variables (self.model, self.color and self.mpg)


#3

Is there a way to write this that you don't have to rewrite all of the instance variables in the child class?


#4

that answer i wrote here:


#5

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

i did it this way but is there a shorter way?


#6

yes, i covered it in the topic i linked to:


#7

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