Overriding


#1





My question is why is it overriding ? can anyone explain how the flow of the code works?

NA

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    def display_car():
        return "This is a %s %s with %s MPG." %(self.color,self.model,self.mpg)
    def drive_car(self):
        self.condition = "used"
        return self.condition
class ElectricCar(Car):
    def __init__(self,battery_type,model,color,mpg):
          self.battery_type=battery_type
          self.model = model
          self.color = color
          self.mpg = mpg
    def drive_car(self):
        condition = "like new"
print my_car.condition
my_car.drive_car()
print my_car.condition
          
my_car = ElectricCar("molten salt","DorLean","Silver",88)




Replace this line with your code.


#2

@ananyapandey ,

As you defined a new __init__ method and a new drive_car method in the ElectricCar class, you were overriding the original methods of the same name that were defined in the superclass, which is Car. If you instantiate and access a Car, the original methods would execute. However, if you instantiate and access an ElectricCar, the overridden methods, as defined for that class, would execute instead.

Now, when you do this ...

my_car = ElectricCar("molten salt","DorLean","Silver",88)

... and then this ...

my_car.drive_car()

... those methods, as defined for the ElectricCar class, are called.

This call should precede the other accesses to my_car ...

my_car = ElectricCar("molten salt","DorLean","Silver",88)

Also check the spelling of "DorLean" in the above.

EDIT (November 12, 2016):
Arrange the statements in this order ...

# Create an instance of ElectricCar.
# The __init__ method of ElectricCar will get called.
my_car = ElectricCar("molten salt" ,"Delorean", "Silver", 88)
# Now, we can access my_car.
print my_car.condition
# Call the drive_car method on my_car.
# The drive_car method of the ElectricCar class will execute.
my_car.drive_car()
print my_car.condition

#3

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