LearnFrenzy
Sign in Take a free test

Inheritance and Polymorphism · Inheritance and Polymorphism Coding Problems · Question 3

Vehicle rental cost with polymorphism in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Model Car, Bike and Bus rentals that each compute their rental cost differently, and print a bill for several bookings.

Solution
main.py Run
class Vehicle:
    rate = 0
    def __init__(self, days):
        self.days = days
    def cost(self):
        return self.rate * self.days

class Car(Vehicle):
    rate = 1500

class Bike(Vehicle):
    rate = 400
    def cost(self):                       # helmet charge on top
        return super().cost() + 100

class Bus(Vehicle):
    rate = 6000
    def cost(self):                       # 10% off for 3 days or more
        base = super().cost()
        return base * 0.9 if self.days >= 3 else base

bookings = [Car(2), Bike(3), Bus(4), Bus(1)]
for b in bookings:
    print(f"{type(b).__name__:<5}{b.days} day(s): Rs {b.cost():,.0f}")
print(f"Total: Rs {sum(b.cost() for b in bookings):,.0f}")

Output Verified by running it on Python 3

Car  2 day(s): Rs 3,000
Bike 3 day(s): Rs 1,300
Bus  4 day(s): Rs 21,600
Bus  1 day(s): Rs 6,000
Total: Rs 31,900

The rate is a class attribute overridden per subclass; Bike and Bus extend cost() with super().

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links