9.Inheritance


#1


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

Error: Oops, try again. my_car does not appear to be an instance of ElectricCar.
NameError: name 'ELectricCar' is not defined


I cannot figure out the origin of errors


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 %d 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,battery_type):
        self.battery_type = battery_type
        
my_car=ElectricCar("molten salt","model","color","mpg")


#3

here:

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

init has one parameter, but when you create an instance you supply 4 arguments, how does that work?


#4

My question exactly.

The __init__ method should take all the parameters, assign the battery type in the local instance, and pass the remaining parameters to the super class.

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

#5

That's right! But shouldn't the child class inherit all the member variables of the parent class? Why do we need to initialize them again in the child class?


#6

well, yes and no. If ElectricCar wouldn't have an init method, the parent init method would be called, by adding an init method to ElectricCar you overwrite init of Car, so you have to initialize all variable again, ideally you would use super() but this hasn't been covered yet


#7

3 posts were split to a new topic: Make sure you've defined a new ElectricCar class


#8