Lesson 15: Classes & Objects
Up until now, you have been writing procedural code. Python also supports Object-Oriented Programming (OOP). This allows us to create our own custom blueprints that bundle data (variables/attributes) and actions (functions/methods) together into a single unit.
1. What is a Class and an Object?
- Class: A blueprint or template (for example, a blueprint for a car).
- Object: A real instance built from that blueprint (for example, your specific red Toyota).
2. What is a Constructor? (__init__)
The constructor is a special method inside a class named __init__. Python automatically runs this method the exact moment you create a new object from your class.
We use the constructor to set up initial starting values (attributes) for our object. The word self represents the specific individual object you are currently creating or interacting with.
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 start_engine(self):
print(f"The {self.color} {self.brand} is starting up!")
3. Creating Objects (Instantiation)
Once your class is built, you create objects by calling the class name and passing the required arguments into the constructor:
# Creating objects from the Car class
car1 = Car("blue", "Fiat 600", 50, "2B1 1354", 5.8)
car2 = Car("silver", "Octavia", 60, "1BL 6069", 6.0)
4. Using Classes Across Different Files (main.py)
In real-world programming, you won't write all your code in a single file. You usually keep your classes in their own separate files (modules) and run your program from a main file.
For example, if you save your Car class inside a file named car.py, you can easily use it inside your main.py file by importing it:
# Inside your main.py file:
from car import Car
car1 = Car("blue", "Fiat 600", 50, "2B1 1354", 5.8)
car2 = Car("silver", "Octavia", 60, "1BL 6069", 6.0)
car1.refuel(65)
print(car1)
car1.drive(120)
print(car1)
Want XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 15