Difficulty in inheritance


#1



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


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):
        self.condition='used'
    
class ElectricCar(Car):
    def __init__(self,battery_type):
        super(ElectricCar,self).__init__(model,color,mpg)
        self.battery_type=battery_type

my_car=Car('DeLorean','silver',88)
my_car= ElectricCar('molten salt')


#2

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.


#3

Thanks appylpye for the clarification


#4

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