CodeStart / Python Course / Lesson 17

Lesson 17: Project: Car Class

Module 6: Object-Oriented Python & Project · about 25 min · free

Project Assignment

Write a Car class from which you can create specific instances (objects), cars. Each car will have the following properties: color, brand, tank capacity, license plate, odometer reading (starts at 0 when the car is created), fuel level, and average fuel consumption.

We will need to print information about cars in a readable format. Also prepare methods for refueling the tank (only up to the available free space in the tank!), calculating the car's driving range, driving a requested number of kilometers, and a graphical "drive" simulation method—which draws a dot for every 10 km driven, with a 0.5s delay.

Try using the class by creating, for example, two cars, refuel both (perhaps not all the way to a full tank), print information about both on the screen, drive the first car 50 km, and drive the second car as many kilometers as you have fuel in the tank. If the fuel runs out, print the car's license plate with the addition: "out of fuel!".

1. The Car Class Implementation (car.py)

import time

class Car:
    def __init__(self, color, brand, tank_capacity, plate, avg_consumption):
        self.color = color
        self.brand = brand
        self.tank_capacity = tank_capacity
        self.plate = plate
        self.fuel_level = 5
        self.consumption = avg_consumption
        self.odometer = 0

    def __str__(self):
        return f"{self.color.capitalize()} {self.brand} with plate {self.plate}, fuel: {self.fuel_level} liters, odometer: {round(self.odometer, 1)} km."

    def refuel(self, liters):
        if self.tank_capacity - self.fuel_level >= liters:
            self.fuel_level += liters
            refueled_amount = liters
        else:
            refueled_amount = self.tank_capacity - self.fuel_level
            self.fuel_level = self.tank_capacity
        return refueled_amount

    def get_range(self):
        return self.fuel_level / self.consumption * 100

    def drive(self, kilometers):
        if kilometers <= self.get_range():
            self.odometer += kilometers
            self.fuel_level -= (kilometers / 100) * self.consumption
            self.draw_drive(kilometers)
        else:
            self.odometer += self.get_range()
            self.draw_drive(round(self.get_range()))
            self.fuel_level = 0
            print(f"Car {self.plate} - out of fuel!")

    def draw_drive(self, kilometers):
        dot_count = kilometers // 10
        for i in range(int(dot_count)):
            print(". ", end="")
            time.sleep(0.5)
        print()

2. Using the Car Class (main.py)

from car import Car

auto1 = Car("blue", "Fiat 600", 50, "2B1 1354", 5.8)
auto2 = Car("silver", "Octavia", 60, "1BL 6069", 6.0)

auto1.refuel(65)
print(auto1)
auto1.drive(120)
print(auto1)

Want XP, levels and progress tracking? Play this lesson in the CodeStart game.

Play Lesson 17