Inheritance: name 'self' isn't defined error


#1



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
my_car.drive_car()
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")


#2

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?


#3

Maybe you could call it with Car?

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


#4

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


#5

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.


#7

@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.


#8

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