Search⌘ K

Solution: Vehicle Management System

Learn to implement an object-oriented vehicle management system in Python. Understand how to create a base class with common attributes and extend it using inheritance, applying polymorphism to override methods for different vehicle types.

We'll cover the following...

Solution

Let’s explore the solution to the problem of the vehicle management system.

Python 3.10.4
# Base Class
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def display_info(self):
print("Subclasses should implement this method")
# Derived Class Car
class Car(Vehicle):
def __init__(self, make, model, num_doors):
super().__init__(make, model)
self.num_doors = num_doors
def display_info(self):
print(f"Car - Make: {self.make}, Model: {self.model}, Number of doors: {self.num_doors}")
# Derived Class Motorcycle
class Motorcycle(Vehicle):
def __init__(self, make, model, type_of_handlebars):
super().__init__(make, model)
self.type_of_handlebars = type_of_handlebars
def display_info(self):
print(f"Motorcycle - Make: {self.make}, Model: {self.model}, Type of Handlebars: {self.type_of_handlebars}")
# Derived Class Truck
class Truck(Vehicle):
def __init__(self, make, model, payload_capacity):
super().__init__(make, model)
self.payload_capacity = payload_capacity
def display_info(self):
print(f"Truck - Make: {self.make}, Model: {self.model}, Payload Capacity: {self.payload_capacity}kg")
# Main Program
def main():
vehicles = [
Car("Toyota", "Corolla", 4),
Motorcycle("Yamaha", "MT-07", "Sport"),
Truck("Ford", "F-150", 1000)
]
for vehicle in vehicles:
vehicle.display_info()
main()

Explanation

Here’s the explanation of the code: ...