5 Jul 2025, Sat

Boost Your Python Skills: A Simple Guide to Object-Oriented Programming 2025

Python

Understanding Object-Oriented Programming in Python (With Examples)

Python is a popular programming language because it’s easy to read and powerful to use. One of its strongest features is Object-Oriented Programming, also known as OOP. OOP helps you organize your code by grouping data and actions into “objects”. This makes your programs easier to write, understand, and update.

In this article, we’ll explain the main ideas of OOP in Python: classes, objects, inheritance, encapsulation, and polymorphism. We’ll also show simple examples so you can learn by doing.


What is Object-Oriented Programming?

OOP is a way of writing code where you create objects based on classes. Think of a class as a plan or blueprint, and an object as the thing you build from that plan.

For example, if you have a class called Car, it might include features like color and brand, and actions like driving. Each car you create from this class is an object, with its own color and brand.

📌 Learn Basic Web Development:


Making Classes and Objects

Here’s how to create a class and use it in Python:

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

    def drive(self):
        print(f"The {self.color} {self.brand} is driving.")

# Create two cars
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

car1.drive()
car2.drive()

🚀Output:

The Red Toyota is driving.
The Blue Honda is driving.

In the code, __init__() is a special method that runs when we create a new car. self means the object itself.


Inheritance: Reusing Code

Inheritance means one class can use code from another class. This helps you avoid repeating code.

class Vehicle:
    def __init__(self, brand):
        self.brand = brand

    def honk(self):
        print(f"{self.brand} says beep beep!")

class Car(Vehicle):
    def __init__(self, brand, color):
        super().__init__(brand)
        self.color = color

    def drive(self):
        print(f"The {self.color} {self.brand} is driving.")

car = Car("Ford", "Black")
car.honk()
car.drive()

🚀Output:

Ford says beep beep!
The Black Ford is driving.

The Car class uses code from the Vehicle class. super() lets us call the parent class’s method.


Encapsulation: Protecting Data

Encapsulation means keeping details inside a class so users can’t change them directly. We use underscores to mark variables as protected or private.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private variable

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Not enough money!")

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print("Balance:", account.get_balance())

🚀Output:

Balance: 1300

Here, __balance is private. You can’t change it directly from outside. You have to use methods like deposit() and get_balance().


Polymorphism: Many Forms

Polymorphism means that different classes can use the same method name but do different things. It helps keep code flexible and easy to change.

class Animal:
    def make_sound(self):
        print("Some sound")

class Dog(Animal):
    def make_sound(self):
        print("Bark")

class Cat(Animal):
    def make_sound(self):
        print("Meow")

def animal_sound(animal):
    animal.make_sound()

dog = Dog()
cat = Cat()

animal_sound(dog)
animal_sound(cat)

🚀Output:

Bark
Meow

Even though animal_sound() calls the same method, the result depends on whether the object is a dog or a cat.


Why Use OOP in Python?

  • Organized Code: Easier to understand and manage.
  • Reusable Code: Inheritance lets you avoid repeating yourself.
  • Safer Data: Encapsulation keeps your data safe from unwanted changes.
  • Flexible Programs: Polymorphism allows for more flexible and powerful code.

Real Example: Library System

Let’s look at how OOP can work in a real program, like managing a library.

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.available = True

    def borrow(self):
        if self.available:
            self.available = False
            print(f"You borrowed '{self.title}'.")
        else:
            print(f"'{self.title}' is not available.")

    def return_book(self):
        self.available = True
        print(f"You returned '{self.title}'.")

class Library:
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)

    def list_books(self):
        for book in self.books:
            status = "Available" if book.available else "Borrowed"
            print(f"{book.title} by {book.author} - {status}")

book1 = Book("1984", "George Orwell")
book2 = Book("The Alchemist", "Paulo Coelho")

library = Library()
library.add_book(book1)
library.add_book(book2)

library.list_books()
book1.borrow()
library.list_books()
book1.return_book()
library.list_books()

This example shows how classes help organize the behavior of books and libraries.

📌 Learn More Python: Click here


Final Thoughts

Object-Oriented Programming is a useful way to structure your Python code, especially for bigger programs. It helps you group data and functions together in a neat way. Once you learn OOP, you’ll find your code becomes cleaner, easier to fix, and better to grow over time.

By Ansh Yadav

I am Founder and Professional article writer specializing in technology, education, sports, and government topics. With a keen interest in technology and education, I explores the latest trends, innovations, and developments shaping these fields.

Leave a Reply

Your email address will not be published. Required fields are marked *