OOPs, or Object-Oriented Programming (OOP), is a programming paradigm that organizes code around objects rather than functions or logic. Objects are instances of classes, which combine data (attributes) and behavior (methods). The main idea is to model real-world entities in a structured, reusable way. Python supports OOP fully, even though it’s dynamically typed.
Core Principles of OOP #
- Encapsulation – Bundling data and methods that operate on that data into a single unit (class) and restricting access using public, protected, and private attributes.
- Abstraction – Hiding internal details and exposing only necessary functionalities.
- Inheritance – Creating a new class from an existing class, reusing code, and extending functionality.
- Polymorphism – Allowing objects to be treated as instances of their parent class, enabling method overriding or operator overloading.
OOP in Python – Implementation Example #
filename.python
# Base Class
class Employee:
def __init__(self, name, salary):
self.name = name # public attribute
self.__salary = salary # private attribute
# Encapsulation & Abstraction
def get_salary(self):
return self.__salary
def set_salary(self, amount):
if amount > 0:
self.__salary = amount
def work(self):
print(f"{self.name} is working.")
# Derived Class – Inheritance
class Manager(Employee):
def work(self): # Polymorphism – method overriding
print(f"{self.name} is managing the team.")
# Objects
emp = Employee("Aswini", 5000)
mgr = Manager("Kumar", 10000)
emp.work() # Employee's method
mgr.work() # Manager's overridden method
print(emp.get_salary()) # Access private attribute through getter
How OOP Concepts Apply Here #
- Encapsulation:
__salaryis private and accessed throughget_salary()/set_salary(). - Abstraction: Users of
Employeedon’t need to know how salary is stored internally. - Inheritance:
Managerinherits fromEmployee, reusing attributes and methods. - Polymorphism:
work()method behaves differently forEmployeeandManager.
Challenges in Python OOP #
- Python is dynamically typed, so type errors may appear at runtime instead of compile-time.
- Overuse of inheritance can create complex hierarchies that are hard to maintain.
- Name mangling for private attributes is only conventionally enforced, so accidental access is possible.
Alternatives / Enhancements #
- Use composition instead of deep inheritance for better maintainability.
- Use abstract base classes (ABC) for enforcing method implementation in subclasses.
- Use property decorators to manage access to private attributes safely.
In short, Python implements OOP in a very flexible and readable way, letting developers model real-world problems with classes, objects, and methods while supporting encapsulation, abstraction, inheritance, and polymorphism.
