Difficulty in inheritance



NameError: global name 'model' is not defined

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 %s MPG.'%(self.color,self.model,self.mpg))
    def drive_car(self):
class ElectricCar(Car):
    def __init__(self,battery_type):

my_car= ElectricCar('molten salt')


Hi, @a1301 ,

When you instantiate ElectricCar, you still need to provide all the attribute information, even though it inherits from Car.

You have ...

def __init__(self,battery_type):

... but before the battery_type, you still need model, color, and mpg.

Then, when you create the instance, which you try to do, here ...

my_car= ElectricCar('molten salt')

... you must pass it the values, 'DeLorean','silver', and 88, in addition to 'molten salt'.

The point of the inheritance is not to force you to choose the same model, color, and mpg rating as your original Car, when you buy a new ElectricCar. The same properties will still be there for you to choose, but you might want to buy a 'Tesla' instead of a 'DeLorean'.

EDIT - The author of this exercise chose to retain the mpg property in the ElectricCar, but it is not clear why. After all, if the car is completely electric, there are no gallons of gasoline. Maybe it is really a hybrid. In any case, that design decision is at the discretion of the author.


Thanks appylpye for the clarification


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