Class inheritance


#1



https://www.codecademy.com/courses/python-intermediate-en-egNXj/1/3?curriculum_id=4f89dab3d788890003000096#
Actually i have executed the code with the help of certain posts..but still have doubt on that..i hope anyone will help..

we were inheriting the member variables from the parent class..then what is the need of declaring variables again in the child class??


here is my 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):
        print "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("DeLorean", "silver", 88, "molten salt")


#2

condition is a member/class variable, you mean the instance variable (model, color and mpg)?

well, if ElectricCar wouldn't have a init method, the init method of Car would be called. By adding an init to ElectricCar, you overwrite the init method of Car, so you have to initialize all instance variable again

ideally, you would super(), which allows you to call parent methods


#3

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