Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 9 - Object-Oriented Programming (OOP)

9.1 Introduction To OOP Concepts

Think of a car. It's a real-life object with various properties like color, speed, and more. In programming, we can conceptualize the car as a class.

Now, imagine you're in a car showroom where you find two color variations of the same car model. One is blue, and the other is red.

Here, the blue car and the red car are two distinct objects instantiated from the same car class.

This concept is central to Object-Oriented Programming (OOP), which emphasizes organizing code into reusable and modular components, mirroring real-world objects and their interactions.

While we won't go in-depth into OOP concepts here, it's worth understanding classes and objects as you'll encounter them frequently in Python code.

Classes and Objects

Classes and Objects are fundamental components of OOP.

A Class serves as a blueprint for creating objects. It defines the attributes (data) and methods (behavior) that objects of the class will have.

An Object is an instance of a Class. It encapsulates data (attributes) and behaviors (methods).

Consider the following example:

class Car:
    def __init__(self, color, model):
        self.color = color
        self.model = model

# Creating objects (instances) of the Car class
car1 = Car("Red", "V16")
car2 = Car("Blue", "V17")

# Printing car details
print("Car 1:", car1.color, car1.model)
print("Car 2:", car2.color, car2.model)

In this example, we defined a Car class with color and model attributes. We then instantiated two objects (car1 and car2) from this class, each with different color and model attributes.

Try it yourself: Modify the above code to create another car object with a different color and model. Then print the details of the new car.