...

/

Solution: The Final Challenge

Solution: The Final Challenge

Review the solution for the vehicle management system challenge.

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:

  1. Encapsulation and rental management: The Vehicle class manages its own rental status and due date. When a vehicle is rented (using rent()), its status is updated and the due date is set to seven days from the current date. Returning a vehicle clears this status, ensuring ...