Worksheet 7 - OOP Class Car example

From Sensors in Schools
Jump to navigation Jump to search

Car Class

Here’s a simple Python program demonstrating object-oriented programming (OOP) concepts. This program defines a basic Car class with attributes and methods to simulate a car's functionality. The program allows for easy expansion and modification.

Simple Python Program: Car Class

# Simple Car Class Example

class Car:
    def __init__(self, make, model, year):
        """Initialize the attributes of the car."""
        self.make = make          # The manufacturer of the car
        self.model = model        # The model of the car
        self.year = year          # The manufacturing year of the car
        self.odometer_reading = 0 # Initialize the odometer reading to 0

    def describe_car(self):
        """Return a neatly formatted descriptive name."""
        return f"{self.year} {self.make} {self.model}"

    def read_odometer(self):
        """Print a statement showing the car's mileage."""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage):
        """Set the odometer to the given value."""
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self, miles):
        """Add the given amount to the odometer."""
        if miles > 0:
            self.odometer_reading += miles
        else:
            print("You can't increment by a negative value!")


if __name__ == '__main__':
    # Create an instance of the Car class
    my_car = Car('Toyota', 'Corolla', 2020)

    # Print the description of the car
    print(my_car.describe_car())

    # Update the odometer and read the mileage
    my_car.update_odometer(15000)
    my_car.read_odometer()

    # Increment the odometer
    my_car.increment_odometer(500)
    my_car.read_odometer()

    # Attempt to roll back the odometer (this will show an error)
    my_car.update_odometer(10000)  # This should show a warning


Explanation of the Code

Class Definition: Car

The class is defined using the class keyword. The __init__ method initializes the car’s attributes, such as make, model, year, and odometer_reading.

Methods:

  • describe_car(self): Returns a string describing the car in a formatted way.
  • read_odometer(self): Prints the current mileage of the car.
  • update_odometer(self, mileage): Updates the odometer reading if the new mileage is greater than or equal to the current reading.
  • increment_odometer(self, miles): Increases the odometer reading by a specified number of miles, only if the value is positive.

Main Script:

  • An instance of the Car class is created (named my_car).
  • The program prints the description of the car, updates the odometer, and shows how to use the various methods defined in the class.
  • The program also demonstrates error handling when attempting to roll back the odometer.

Expanding the Program

Here are some ideas on how to expand this program:

Add More Attributes:

  • Include attributes like color, fuel_type, or mileage_per_gallon.
  • Create Derived Classes: Create subclasses, such as ElectricCar, that inherit from the Car class and add new methods or attributes (e.g., battery capacity).
  • Implement a Maintenance Log: Add methods to track maintenance activities or repairs.
  • Add User Input: Allow users to input car details when creating a new car object.

This simple program provides a solid foundation for learning OOP in Python and can easily be expanded upon as you gain more experience!