Object-oriented programming (OOP) organises code around objects that combine data and behaviour. Python supports the four OOP pillars: encapsulation, abstraction, inheritance and polymorphism. Most Python libraries – including pandas DataFrames and scikit-learn models – are built this way.
What You Will Learn
- The four pillars of OOP
- Encapsulation with private attributes and @property
- Abstraction with base classes
- Polymorphism with a common interface
- Why OOP matters in data science
Prerequisites
The Four Pillars
| Pillar | Idea | Python tool |
|---|---|---|
| Encapsulation | Keep data safe inside the object and expose controlled methods | __private names, @property |
| Abstraction | Show what an object does, hide how | Base classes, abc.ABC |
| Inheritance | Build new classes from existing ones | class Child(Parent) |
| Polymorphism | Same method name, different behaviour | Method overriding, duck typing |
Encapsulation
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # private (name-mangled)
def deposit(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
self.__balance += amount
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient balance")
return
self.__balance -= amount
@property
def balance(self): # read-only access
return self.__balance
acc = BankAccount("Karan", 1000)
acc.deposit(500)
acc.withdraw(2000)
acc.withdraw(300)
print(acc.balance)
try:
print(acc.__balance)
except AttributeError as e:
print("AttributeError:", e)
Insufficient balance 1200 AttributeError: 'BankAccount' object has no attribute '__balance'
Explanation: The balance can only change through deposit and withdraw, which check the rules. Two underscores trigger name mangling, so acc.__balance is not reachable from outside. @property lets users read acc.balance like an attribute but not assign it.
Abstraction and Polymorphism
class Shape:
def area(self):
raise NotImplementedError
class Rectangle(Shape):
def __init__(self, w, h): self.w, self.h = w, h
def area(self): return self.w * self.h
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return round(3.14159 * self.r ** 2, 2)
for s in [Rectangle(4, 5), Circle(3)]:
print(type(s).__name__, s.area())
Rectangle 20 Circle 28.27
Explanation: Shape defines the interface (abstraction). Each subclass implements area() its own way, and the loop calls s.area() without caring which shape it is – that is polymorphism. For a strict interface use from abc import ABC, abstractmethod.
OOP in Data Science
Every scikit-learn model is an object with the same methods – fit(), predict(), score() – so you can swap Logistic Regression for a Random Forest without changing the rest of your code. That is polymorphism at work.
Series
Python series: What is Python · Installation · Syntax · Variables · Operators · Decisions · Loops · Strings · Lists · Dictionary · Functions · Lambda · Modules · Files · Exceptions · OOP · Classes & Objects · Inheritance · Decorators · Generators · Virtual Environments
Interview Questions
Q: What are the four pillars of OOP?
Encapsulation, abstraction, inheritance and polymorphism.
Q: Does Python have truly private attributes?
No; double underscores cause name mangling (_Class__name) that discourages, but does not prevent, outside access.
Q: What is duck typing?
If an object has the needed method, it can be used, regardless of its class.
Practice Exercises
- Add a Triangle class to the shapes example.
- Add a transaction history list to BankAccount and a method to print it.
Summary
OOP groups data and behaviour into objects. Encapsulation protects data, abstraction defines interfaces, inheritance reuses code and polymorphism lets different objects share one interface.
Next: Inheritance
Machine Learning Tutorials, Courses and Certifications