OOP is the most popular programming paradigm. We explain Abstraction, Encapsulation, Inheritance, and Polymorphism using simple, real-world examples and Python structures.
The Four Pillars of OOP
1. **Encapsulation**: Wrapping variables and methods into a single unit (Class) and restricting direct access (using private variables) to protect state.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # Private variable (Encapsulation)
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
Let's trace how the system enforces Encapsulation: account = BankAccount("John", 500) instantiates the class. If you try to run print(account.__balance) directly from outside, Python blocks access with an AttributeError because of name mangling, securing the balance from unsafe direct mutations.
2. **Inheritance**: Allowing a new class (child) to adopt variables and methods of an existing class (parent), eliminating code duplication.
3. **Polymorphism**: The ability of an object to take many forms (e.g. method overloading and overriding).
4. **Abstraction**: Hiding internal implementation complexities and exposing only a clean, simple interface.