Object - Oriented Programming(OOP) in Python
Definition: Object - Oriented Programming is a programming paradigm that organizes code into objects — bundles of data(attributes) and behavior(methods).OOP models real - world entities and their interactions, making code modular, reusable, and maintainable.
---
Why OOP in Data Science ?
- Libraries like Scikit - learn , TensorFlow , and Pandas are built using OOP.
- Understanding OOP helps you: read library source code, build custom models and pipelines, and write production - quality code.
---
Core Concepts
1. Class and Object
Class: A blueprint or template for creating objects.It defines properties(attributes) and behaviors(methods).
Object: An instance of a class — a specific realization of the blueprint.
class Student:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute
def greet(self): # Method
return f"Hi, I'm {self.name}, age {self.age}"
# Creating objects
s1 = Student("Rahul", 21)
s2 = Student("Priya", 22)
print(s1.greet()) # Hi, I'm Rahul, age 21
Key Points:
initis the constructor — called automatically when an object is created.selfrefers to the current instance of the class.
---
2. The Four Pillars of OOP
Pillar 1: Encapsulation
Definition: Bundling data and methods together and restricting direct access to some of the object's components. This protects data from unintended modification.
Access Modifiers:
| Convention | Meaning | Example |
|---|---|---|
name | Public (accessible everywhere) | self.name = "Rahul" |
_name | Protected (convention: internal use) | self._salary = 50000 |
__name | Private (name mangling) | self.__password = "secret" |
Getter and Setter Methods:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private
def get_balance(self): # Getter
return self.__balance
def deposit(self, amount): # Setter-like
if amount > 0:
self.__balance += amount
---
Pillar 2: Inheritance
Definition: A mechanism where a new class (child/derived) inherits properties and methods from an existing class (parent/base). It promotes code reuse and establishes a natural hierarchy.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
class Dog(Animal): # Dog inherits from Animal
def speak(self): # Override parent method
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
d = Dog("Buddy")
print(d.name) # Buddy (inherited)
print(d.speak()) # Woof! (overridden)
Types of Inheritance:
| Type | Description | Example |
|---|---|---|
| Single | Child inherits from one parent | Dog → Animal |
| Multiple | Child inherits from multiple parents | Child → Father, Mother |
| Multilevel | Chain: Grandparent → Parent → Child | Animal → Dog → Puppy |
| Hierarchical | Multiple children from one parent | Animal → Dog, Cat, Bird |
---
Pillar 3: Polymorphism
Definition: "Many forms." The same method name behaves differently depending on the object that calls it. This allows a single interface to work with different data types.
Example — Method Overriding:
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
print(f"{animal.name}: {animal.speak()}")
# Buddy: Woof!
# Whiskers: Meow!
Both call .speak(), but the behavior is different — that's polymorphism.
Built-in Polymorphism:
len()works on strings, lists, and tuples.+operator works for numbers (addition) and strings (concatenation).
---
Pillar 4: Abstraction
Definition: Hiding complex implementation details and showing only the essential features. Users interact with a simplified interface without needing to know the internal workings.
from abc import ABC, abstractmethod
class Shape(ABC): # Abstract class
@abstractmethod
def area(self): # Abstract method
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# shape = Shape() # Error! Can't instantiate abstract class
c = Circle(5)
print(c.area()) # 78.5
---
Special (Dunder) Methods
Python classes support special methods (double underscore methods) that define built-in behavior:
| Method | Purpose | Example |
|---|---|---|
init | Constructor | Student("Rahul", 21) |
str | String representation | print(obj) |
repr | Developer representation | In debugger/REPL |
len | Length | len(obj) |
add | Addition operator | obj1 + obj2 |
eq | Equality check | obj1 == obj2 |
---
OOP Pillars Summary
| Pillar | Purpose | Mechanism |
|---|---|---|
| Encapsulation | Protect data | Access modifiers, getters/setters |
| Inheritance | Reuse code | Child class extends parent class |
| Polymorphism | Flexible behavior | Same method name, different behavior |
| Abstraction | Hide complexity | Abstract classes and methods |
Summary
- OOP organizes code into classes (blueprints) and objects (instances).
- The four pillars are Encapsulation, Inheritance, Polymorphism, and Abstraction.
initis the constructor;selfrefers to the current instance.- Inheritance promotes code reuse; Polymorphism enables flexible interfaces.
- Python's data science libraries (Scikit-learn, Pandas) are built with OOP.