Solution: The Final Challenge
Understand how to apply core object-oriented principles by reviewing a full vehicle rental system solution. Learn encapsulation for rental status, inheritance with method overriding, and composition to manage customers and vehicles. This lesson guides you through careful code organization and prepares you for advanced OOP projects.
We'll cover the following...
We'll cover the following...
Below is the complete solution to the challenge:
from datetime import datetime, timedelta
class Vehicle:
def __init__(self, brand, model, vehicle_type):
self.brand = brand
self.model = model
self.vehicle_type = vehicle_type
self.is_rented = False
self.rental_due_date = None
def rent(self, customer):
# Allow a customer to rent the vehicle if available
if not self.is_rented:
self.is_rented = True
self.rental_due_date = datetime.now() + timedelta(days=7)
customer.rented_vehicle = self
print("%s rented %s %s, due back on %s." % (customer.name, self.brand, self.model, self.rental_due_date.date()))
else:
print("%s %s is already rented." % (self.brand, self.model))
def return_vehicle(self):
# Return the vehicle and clear the due date
self.is_rented = False
self.rental_due_date = None
print("%s %s has been returned." % (self.brand, self.model))
def __str__(self):
return "%s %s (%s)" % (self.brand, self.model, self.vehicle_type)Now that you have seen the solution, let’s understand it in detail:
Encapsulation and rental management: The
Vehicleclass manages its own rental status and due date. When a vehicle is rented (usingrent()), its status is updated and the due date is set to seven days from the current date. Returning a vehicle clears this status, ensuring ...