Inheritance: name 'self' isn't defined error


I stuck at this exercise:

Error is NameError: name 'self' isn't defined and "Oops, try again. my_car does not appear to be an instance of ElectricCar."

I don't understand what I do wrong. Please, help me.

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, 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,battery_type):
        self.battery_tyoe = battery_type
    super(ElectricCar, self).__init__(model, color, mpg)
my_car = ElectricCar("DeLorean", "Red", 15, "molten salt")


As first. You have spelled battery_type as battery_tyoe. As secondary, why are you calling to init(model, color, mpg) using super() method? Maybe you could call it with Car?


Maybe you could call it with Car?

How I can do it? I mean, how it looks in the code?


You are calling to __init __(model, color, mpg) as you did, but you have to call to it with Car.


Like this ?

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

It's the solution, thanks you for idea.


@papusalaatti was referring to another way that you could do this ...

Here's how you could do it ...

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

Notice that when we call __init__ directly from the class object, which is Car in this case, we must pass the appropriate new instance of ElectricCar as the first argument. Since we established self as the name of that instance here ...

def __init__(self, model, color, mpg, battery_type):

... we use that name to represent the instance in the direct call to __init__, as exemplified above.


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