Why repeat the init within init why


#1



9. Inheritance - init car.ini why

(Code works, not sure WHY?)

I didn't think I needed init inside an init statement... ? I'm looking specifically at the ElectricCar init


# Class Defined
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 " + self.color + " " + self.model + " with " + str(self.mpg) + " MPG."
    def drive_car(self):
        self.condition = "used"
# """ New ElectricCar SubClass Object of Car """
class ElectricCar(Car):
    # by adding another variable this car needs 4 inputs
    # in order:     <newObject> = ElectricCar
    # ("<model>","color",<mpg>,"battery_type")
    # 
    def __init__(self, model, color, mpg, battery_type):
    # NOT SURE WHY THIS IS NEEDED ??? (already from(Car))
        Car.__init__(self,model,color,mpg)
        self.battery_type = battery_type
    # code didn't run without.

# New Object (sub-object) from ElectricCar
# in order:     <newObject> = ElectricCar
# ("<model>","color",<mpg>,"battery_type")
my_car = ElectricCar("SmartCar", "blue", 44, "molten salt")
print my_car.model
# more print statements...


#2

It is necessary to populate the attributes of the parent class instance. Even though the new instance may be an ElectricCar, it still inherits from Car so those attributes need values as well.


#4