Inheritance Bug


**I keep getting this error when I run my code.** "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, str(self.mpg))
    def drive_car(self):
        self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.condition

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

my_car = ElectricCar("Prius", "silver", 88, "molten salt")
print my_car.battery_type


Okay, But I don't get why i should set all the other properties as i thought that was the whole point of inheritance.:worried:


You overrode the thing that sets that attribute, overriding something means it should no longer be in effect


How do you know if you have override a class? In the Codecademy courses, it pretty much told us when to write it, so I'm not quite sure how to recognize it myself. Thank you for your help.


The class is inherited, not overridden. It's members of the class that are overridden, in this case __init__
When you access an attribute of an object it starts searching in its own attributes, then its own class's attributes, and then in parent classes


Okay..thanks for clearing my confusion! But when a function is overridden, we have to declare parts of it again, right? How can we identify when, or when not to do that?


If you override __init__ then it's not going to use parts of the parent's __init__, it will run the first one it finds


By parts I had meant multiple function in the parent class, sorry I didn't clarify. For example, if we have a parent class with say 5 different functions, would all of those be overridden in the subclass, or just specific ones? If it is just specific ones, then how do we know which ones are going to be overridden, and which will not be overriden? Thank you for helping me understand this by the way.


For each method python will use the one it finds first, so if it's defined in the object itself, or the objects class, then it won't look in the parent class. For anything that you don't redefine earlier in the search path, the parent version gets used.


That clears my confusion. Thank you for your help. :slight_smile:


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