Inheritance


#1

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 "+ str(self.mpg) +"              MPG"%(self.color,self.model)
    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("Tamara", "golden", 90,"molten salt")

error
my_car does not have a model member variable.

I am not understanding the mistake. Can someone guide me?


#2

Hi @karishma97,

The main issue appears to be right here:

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

Do you see that space after mpg? That is whitespace and it may be interfering with the syntax in your code. Remove it.

Also, you still need to add more self.PARAMETER = PARAMETER statements. You should have one for each parameter except for self.


Also, why do you have so many spaces before MPG in:

return "This is a [%s] [%s] with "+ str(self.mpg) +"              MPG"%(self.color,self.model)

Not only are they unnecessary, they are really distracting. It's honestly sort of triggering me.


#3

As above, you need to set the args to something, You could do this through adding self.arg = arg within the ElectricCar init or you could use inheritance through super(), for example.

So, you could simply add define them in the ElectricCar init like so:

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

Or you could inherit with super() like so:

class ElectricCar(Car):
    def __init__(self, model, color, mpg , battery_type):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model,color,mpg) # Python 2.
#       super().__init__(model,color,mpg) would work in Python 3.

Or inherit from a base class like so:

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

I'd suggest you read up on the last two methods to get a proper feel for the differences between them, etc. As a lot can and has been written on them. I wouldn't have mentioned them but for the fact, it seems like that was what you are trying to do.


#4

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