Method overriding – Super().<method> vs Class().<method>

Question:

Hi I’m practicing method overriding and trying to override fare method of parent class in the child class. Basically the idea is to override the parent class fare method
I know if I use super()., it would work but I’m curious why calling Vehicle().fare() doesn’t work but super().fare() works. Thank you all

class Vehicle:
    def __init__(self, name, mileage, capacity):
        self.name = name
        self.mileage = mileage
        self.capacity = capacity
    
    def fare(self):
        return self.capacity * 100

class Bus(Vehicle):
    def fare(self):
        return int(Vehicle().fare() + Vehicle().fare()*0.1)

School_bus = Bus("School Volvo", 12, 50)
print("Total Bus fare is:", School_bus.fare())
Asked By: AmirHossein Rd

||

Answers:

Calling Vehicle() means that you are calling the constructor for the class Vehicle (docs). This behavior is the same anywhere in your code. This means that if you tried doing Vehicle().fare() you would be creating a new instance of the Vehicle class and calling the fare() method on that new instance. This new instance has no relationship to your Bus class.

This would also result in an error because you did not provide the 3 required arguments (name, mileage, capacity) to the Vehicle constructor.

super() is a special function that allows for a child class to call a method or constructor using the implementation in the parent class. This can be useful when you are trying to use method overloading because it removes ambiguity. It clarifies that you are trying to call a method from the parent, and not the child.

In this case, super() is being used to reference the implementation of fare() in the Vehicle class.

If you were creating a new method in the Bus class and were to call self.fare() this would call the implementation in Bus, but if you were to call super().fare() it would call the implementation in Vehicle.

Also, ignore the mean comments. Object Oriented Programming can be very tricky to learn!

Answered By: alieb
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.