Python Advanced: Object-Oriented Programming (OOP)

Goal of the Day

Today you will learn:

By the end, you will be able to write your own classes to make complex programs organized and modular.

Step 1: What is a Class?

A class is a blueprint or template for objects.

An object is a concrete instance of that class.

Real-life example:

Step 2: Creating a Class


class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(self.name + " is barking!")

Explanation:

Step 3: Creating an Object


my_dog = Dog("Bello", 5)

"Bello" → name
5 → age
my_dog → object

Step 4: Calling Methods


my_dog.bark()

Output:


Bello is barking!

Explanation:

Step 5: Modifying Attributes


my_dog.age = 6
print(my_dog.age)

Output:


6

Practice Tip:

Step 6: Practice – Car Class


class Car:
    def __init__(self, brand, model, mileage=0):
        self.brand = brand
        self.model = model
        self.mileage = mileage

    def drive(self, km):
        self.mileage += km
        print("The car has driven. New mileage:", self.mileage)

Step 7: Creating Objects of the Car Class


my_car = Car("BMW", "X5")
my_car.drive(50)

car2 = Car("Audi", "A4", 20000)
car2.drive(100)

Output:


The car has driven. New mileage: 50
The car has driven. New mileage: 20100

Explanation:

Exercise