10. Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm based on objects and classes.

OOP helps:

  • Organize code better
  • Improve reusability
  • Make large applications easier to manage

Classes and Objects


What is a Class?

A class is a blueprint for creating objects.

It defines:

  • Variables (attributes)
  • Functions (methods)

What is an Object?

An object is an instance of a class.


Creating a Class

Syntax

class ClassName:
# attributes and methods

Example

class Student:
pass

Creating Objects

class Student:
pass

s1 = Student()
s2 = Student()

print(s1)
print(s2)

Constructors

A constructor is a special method automatically called when object is created.

Python uses:

__init__()

Example

class Student:

def __init__(self, name, age):
self.name = name
self.age = age

student1 = Student("Aditya", 25)

print(student1.name)
print(student1.age)

Output:

Aditya
25

The self Keyword

self refers to the current object.

Used to access instance variables and methods.


Instance Variables

Variables unique to each object.

class Car:

def __init__(self, brand):
self.brand = brand

c1 = Car("BMW")
c2 = Car("Audi")

print(c1.brand)
print(c2.brand)

Class Variables

Shared by all objects.

class Employee:

company = "SOA Technology"

def __init__(self, name):
self.name = name

e1 = Employee("Aditya")
e2 = Employee("Rahul")

print(e1.company)
print(e2.company)

Methods in Python

Methods are functions inside classes.


Instance Methods

class Person:

def __init__(self, name):
self.name = name

def greet(self):
print("Hello", self.name)

p1 = Person("Aditya")
p1.greet()

Class Methods

Use @classmethod.

class Demo:

count = 0

@classmethod
def show_count(cls):
print(cls.count)

Demo.show_count()

Static Methods

Use @staticmethod.

class Math:

@staticmethod
def add(a, b):
return a + b

print(Math.add(5, 3))

Inheritance

Inheritance allows one class to acquire properties of another class.


Parent and Child Class

class Animal:

def sound(self):
print("Animal makes sound")

class Dog(Animal):
pass

d = Dog()
d.sound()

Method Overriding

Child class changes parent method behavior.

class Animal:

def sound(self):
print("Animal sound")

class Dog(Animal):

def sound(self):
print("Dog barks")

d = Dog()
d.sound()

Output:

Dog barks

super() Function

Used to call parent class methods.

class Person:

def __init__(self, name):
self.name = name

class Student(Person):

def __init__(self, name, course):
super().__init__(name)
self.course = course

s = Student("Aditya", "Python")

print(s.name)
print(s.course)

Polymorphism

Polymorphism means:

One interface, many forms

Example

class Bird:

def sound(self):
print("Bird sound")

class Sparrow(Bird):

def sound(self):
print("Sparrow chirps")

class Crow(Bird):

def sound(self):
print("Crow caws")

for bird in [Sparrow(), Crow()]:
bird.sound()

Encapsulation

Encapsulation means restricting direct access to data.

Use:

  • Private variables
  • Getter and setter methods

Private Variable

Use double underscore __.

class Bank:

def __init__(self):
self.__balance = 1000

b = Bank()

# print(b.__balance) # Error

Getter and Setter

class Bank:

def __init__(self):
self.__balance = 0

def deposit(self, amount):
self.__balance += amount

def get_balance(self):
return self.__balance

b = Bank()

b.deposit(500)

print(b.get_balance())

Abstraction

Abstraction hides implementation details and shows only essential features.

Python uses abstract classes from abc module.


Example

from abc import ABC, abstractmethod

class Vehicle(ABC):

@abstractmethod
def start(self):
pass

class Car(Vehicle):

def start(self):
print("Car started")

c = Car()
c.start()

Magic Methods

Magic methods are special methods with double underscores.

Also called:

Dunder methods

Common Magic Methods

MethodPurpose
__init__Constructor
__str__String representation
__len__Length
__add__Addition
__del__Destructor

__str__() Method

Defines object string representation.

class Student:

def __init__(self, name):
self.name = name

def __str__(self):
return f"Student name is {self.name}"

s = Student("Aditya")

print(s)

Output:

Student name is Aditya

__len__() Method

class Team:

def __len__(self):
return 5

t = Team()

print(len(t))

Operator Overloading

Using magic methods to customize operators.

class Number:

def __init__(self, value):
self.value = value

def __add__(self, other):
return self.value + other.value

n1 = Number(10)
n2 = Number(20)

print(n1 + n2)

Output:

30

Destructor __del__()

Called when object is destroyed.

class Demo:

def __del__(self):
print("Object destroyed")

d = Demo()

Real-Life Example

Student Management System

class Student:

school = "SOA School"

def __init__(self, name, marks):
self.name = name
self.marks = marks

def display(self):
print("Name:", self.name)
print("Marks:", self.marks)

s1 = Student("Aditya", 90)

s1.display()

Advantages of OOP

✅ Code reusability
✅ Better organization
✅ Easier maintenance
✅ Data security
✅ Real-world modeling