OOPs in Python

Getting your Trinity Audio player ready...

Python is an object-oriented language, which means it supports the principles of Object-Oriented Programming (OOP) such as classes, objects, inheritance, encapsulation, and polymorphism.
OOPs in Python helps make code modular, reusable, and organized — ideal for large and complex projects.

OOPs in Python

What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm where everything is represented as an object that contains data and methods to operate on that data.

Example:

car = {
    "brand": "Toyota",
    "model": "Corolla",
    "year": 2022
}

Here, car has properties — but in OOP, we would create a Car class and then make multiple car objects from it.


Why OOP?

Problem (in Procedural Code)Solution (with OOP)
Hard to manage large codeOrganize into classes
Repeated codeUse inheritance
No data securityEncapsulation
Limited flexibilityPolymorphism

1. Classes and Objects

A Class is a blueprint for creating objects.
An Object is an instance of a class — a real-world entity.

Example:

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    
    def display_info(self):
        print(f"Car: {self.brand} {self.model}")

# Creating objects
car1 = Car("Toyota", "Corolla")
car2 = Car("Tesla", "Model 3")

car1.display_info()
car2.display_info()

Output:

Car: Toyota Corolla
Car: Tesla Model 3

Explanation:

  • __init__() → constructor method (runs automatically when object is created)
  • self → refers to the current instance of the class

2. Class and Instance Variables

  • Class Variables → shared across all objects
  • Instance Variables → unique for each object

Example:

class Student:
    school = "SmartTejas Academy"   # class variable

    def __init__(self, name, grade):
        self.name = name            # instance variable
        self.grade = grade

s1 = Student("Amit", "A")
s2 = Student("Priya", "B")

print(s1.school)  # SmartTejas Academy
print(s2.name)    # Priya

3. Types of Methods in Python

TypeDescriptionExample
Instance MethodOperates on instance datadef display(self):
Class MethodWorks on class-level data@classmethod
Static MethodIndependent utility method@staticmethod

Example:

class MathUtils:
    count = 0

    def __init__(self):
        MathUtils.count += 1

    @classmethod
    def total_objects(cls):
        print(f"Total objects created: {cls.count}")

    @staticmethod
    def add(a, b):
        return a + b

MathUtils.add(5, 7)
obj1 = MathUtils()
obj2 = MathUtils()
MathUtils.total_objects()

Output:

Total objects created: 2

Read More: Date and Time in Python


4. Encapsulation

Encapsulation means protecting data (variables) from direct access and modification.

Example:

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

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

    def get_balance(self):
        return self.__balance

acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance())  # ✅ 1500
print(acc.__balance)      # ❌ AttributeError

✅ Use __ (double underscore) to make a variable private.


5. Inheritance

Inheritance allows a new class (child) to reuse and extend functionality from an existing class (parent).

Types of Inheritance:

  1. Single
  2. Multiple
  3. Multilevel
  4. Hierarchical
  5. Hybrid

Example (Single Inheritance):

class Vehicle:
    def start(self):
        print("Vehicle started")

class Car(Vehicle):
    def drive(self):
        print("Car is driving")

c = Car()
c.start()
c.drive()

Output:

Vehicle started
Car is driving

Read More: Inheritance in Python


6. Method Overriding

If a child class defines a method with the same name as the parent, the child’s method overrides the parent’s version.

Example:

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

class Dog(Animal):
    def sound(self):
        print("Bark Bark!")

d = Dog()
d.sound()

Output:

Bark Bark!

7. Polymorphism

Polymorphism allows methods with the same name to behave differently for different objects.

Example:

class Cat:
    def speak(self):
        return "Meow"

class Dog:
    def speak(self):
        return "Woof"

for animal in [Cat(), Dog()]:
    print(animal.speak())

Output:

Meow
Woof

8. Operator Overloading (Polymorphism in Action)

Python allows you to customize operators (like +, -, <, etc.) for your own classes.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2

print(p3.x, p3.y)

Output:

6 8

9. Abstraction

Abstraction means hiding implementation details and showing only necessary features.

Example:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14 * self.r * self.r

c = Circle(5)
print(c.area())

✅ Output:

78.5

You can’t instantiate abstract classes directly.


10. Example: Employee Management System

class Employee:
    company = "TechCorp"

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display(self):
        print(f"{self.name} earns {self.salary}")

class Manager(Employee):
    def __init__(self, name, salary, department):
        super().__init__(name, salary)
        self.department = department

    def display(self):
        print(f"{self.name} manages {self.department} department and earns {self.salary}")

# Create objects
e1 = Employee("Amit", 50000)
m1 = Manager("Priya", 80000, "IT")

e1.display()
m1.display()

Output:

Amit earns 50000
Priya manages IT department and earns 80000

11. Benefits of OOPs in Python

BenefitDescription
ModularityCode organized into reusable classes
ReusabilityUse existing classes in new projects
ExtensibilityAdd new features without breaking existing code
MaintainabilityEasier to debug and update
SecurityEncapsulation protects data

12. Summary Table of Key OOP Concepts

ConceptMeaningKeyword / Example
ClassBlueprintclass Car:
ObjectInstancecar1 = Car()
ConstructorInitialize objectdef __init__()
InheritanceReuse parent classclass Child(Parent)
PolymorphismSame method, different behaviordef sound()
EncapsulationData hiding__private_var
AbstractionHiding details@abstractmethod

Real-World Use Cases of OOPs in Python

IndustryExample
Data ScienceModel wrappers, pipeline classes
Web DevelopmentDjango Models, Flask Views
AutomationClass-based task managers
Game DevelopmentCharacters, weapons, enemies as objects
AI AssistantsClass-based command, intent, and speech modules

Conclusion

Object-Oriented Programming (OOP) in Python gives structure and flexibility to your code.
Once you master classes, inheritance, and polymorphism — you can easily build large systems like AI assistants, dashboards, and ML frameworks efficiently.

What’s Next?

In the next post, we’ll learn about the Inheritance in Python

Spread the love

Leave a Comment

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

Translate »
Scroll to Top