Inheritance Bug


#1



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

**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
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("Prius", "silver", 88, "molten salt")
print my_car.battery_type


#3

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:


#4

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


#5

Hi,
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.


#6

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


#7

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?


#8

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


#9

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.


#10

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.


#11

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


#12

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