Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Object-Oriented Programming (OOP)

Lesson 21 of 37 in the free Data Science notes on Siksha Sarovar, written by Rohit Jangra.

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:

  • init is the constructor — called automatically when an object is created.
  • self refers 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:

ConventionMeaningExample
namePublic (accessible everywhere)self.name = "Rahul"
_nameProtected (convention: internal use)self._salary = 50000
__namePrivate (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:

TypeDescriptionExample
SingleChild inherits from one parentDog → Animal
MultipleChild inherits from multiple parentsChild → Father, Mother
MultilevelChain: Grandparent → Parent → ChildAnimal → Dog → Puppy
HierarchicalMultiple children from one parentAnimal → 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:

MethodPurposeExample
initConstructorStudent("Rahul", 21)
strString representationprint(obj)
reprDeveloper representationIn debugger/REPL
lenLengthlen(obj)
addAddition operatorobj1 + obj2
eqEquality checkobj1 == obj2

---

OOP Pillars Summary

PillarPurposeMechanism
EncapsulationProtect dataAccess modifiers, getters/setters
InheritanceReuse codeChild class extends parent class
PolymorphismFlexible behaviorSame method name, different behavior
AbstractionHide complexityAbstract classes and methods

Summary

  • OOP organizes code into classes (blueprints) and objects (instances).
  • The four pillars are Encapsulation, Inheritance, Polymorphism, and Abstraction.
  • init is the constructor; self refers to the current instance.
  • Inheritance promotes code reuse; Polymorphism enables flexible interfaces.
  • Python's data science libraries (Scikit-learn, Pandas) are built with OOP.