Object-Oriented Programming (OOP) is a programming paradigm that allows us to model real-world entities as objects. In Python, objects are created from classes, which act as blueprints for creating objects with specific attributes and behaviors.
Let’s explore how to define classes and create objects in Python:
# Defining a class class Car: def __init__(self, brand, model, year): self.brand = brand self.model = model self.year = year def accelerate(self): print("The car is accelerating.") def brake(self): print("The car is braking.") # Creating objects (instances) car1 = Car("Toyota", "Camry", 2020) car2 = Car("Honda", "Civic", 2019) # Accessing object attributes print("Car 1:", car1.brand, car1.model, car1.year) print("Car 2:", car2.brand, car2.model, car2.year) # Calling object methods car1.accelerate() car2.brake()
- We define a class
Carthat represents a car object.
__init__()method is a special method called a constructor, used to initialize the object’s attributes (
year) when it is created.
- We define additional methods (
brake()) that represent the behaviors of a car.
- We create objects (
car2) by calling the class as if it were a function and passing the required arguments to the constructor.
- We access the object attributes using dot notation (
- We call the object methods using dot notation as well.
Now it’s time for a practical task:
Create a class called
Rectangle that represents a rectangle object. The class should have attributes
height, and methods
calculate_perimeter() to compute the area and perimeter of the rectangle, respectively. Create two rectangle objects and test the methods.
Once you’ve completed the task, you can proceed to the next lesson.