15. OOP Concepts: Encapsulation, Inheritance, Abstraction, Polymorphism
OOP: The Four Core Principles
In this lesson, you’ll learn the four main pillars of OOP that help make code cleaner, reusable, secure, and easier to maintain:
- Encapsulation – Protects data by restricting direct access
- Inheritance – Reuses and extends existing code
- Abstraction – Hides complexity and exposes only what matters
- Polymorphism – Allows one interface with many forms
1. Encapsulation
Encapsulation means bundling data and methods inside a class to protect data from accidental modification. It is achieved using private and protected variables.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # Public attribute
self._balance = balance # Protected attribute
def deposit(self, amount):
self._balance += amount
def get_balance(self):
return self._balance
account = BankAccount("John", 1000)
account.deposit(500)
print(account.get_balance()) # 15002. Inheritance
Inheritance allows a class (child) to reuse and extend the behavior of another class (parent). This prevents duplication and supports code reusability.
class Animal:
def speak(self):
return "Animal makes a sound"
class Dog(Animal): # Dog inherits from Animal
def speak(self):
return "Woof!"
d = Dog()
print(d.speak()) # Woof!3. Abstraction
Abstraction hides unnecessary details and exposes only the essential features. In Python, abstraction is implemented using abstract base classes.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def move(self):
pass
class Car(Vehicle):
def move(self):
return "Car is driving"
car = Car()
print(car.move())4. Polymorphism
Polymorphism allows different classes to share the same method name but behave differently. It makes a single interface work for multiple types.
class Cat:
def speak(self): return "Meow"
class Cow:
def speak(self): return "Moo"
for animal in [Cat(), Cow()]:
print(animal.speak())Why These Principles Matter
- Encapsulation → Security
- Inheritance → Reuse
- Abstraction → Simplicity
- Polymorphism → Flexibility
Real World Example
These principles are used in GUI frameworks (like PyQt), JSON serializers (like Django serializers), game engines, data pipelines, and more. OOP is used in large projects because it makes code easier to organize.