Overriding Methods: How can I use super() in my code?


#1


As you can see, I made the ElectricCar class that calls upon the Car class.

However, I should have a way to use the Car's class model, color, and mpg methods without having to explicitly input them into the ElectricCar's init function..... right?

I know I should be able to use super() somehow, but I am not quite sure how to do so. I've read a cuple of resources but am a bit confused. Any help?

Keep in mind, my code works as-is, I just want ta better way to write it.

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 and a %s battery." % (self.color, self.model, str(self.mpg), self.battery_type)
    def drive_car(self):
        self.condition = "used"

class ElectricCar(Car):
    def __init__(self, name, model, color, mpg, battery_type):
        self.name = name
        self.model = model
        self.color = color
        self.mpg = mpg
        self.battery_type = battery_type
    def drive_car(self):
        self.condition = "like new"

my_car = ElectricCar("my_car", "Tesla", "silver", 88, "molten salt")

print my_car.condition
print my_car.drive_car()
print my_car.condition


#2

like this:

super(ElectricCar, self).__init__(model, color, mpg)

#3

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