Lesson 48 of 70 – Python Object Oriented Programming
69%

Python Object Oriented Programming (OOP)

Object Oriented Programming, commonly called OOP, is a programming approach based on objects and classes. Python supports object-oriented programming and allows us to create reusable and well-organized programs.

Note: OOP is especially useful when building large applications because it helps organize data and functionality into reusable objects.

What is Object Oriented Programming?

Object Oriented Programming is a programming style where a program is designed using objects that contain data and behavior.

For example, a student can be represented as an object containing information such as name, age, course, and methods such as displaying student details.

Student

Data:
    name
    age
    course

Behavior:
    display()
    study()

What is a Class?

A class is a blueprint or template for creating objects. It defines the data and behavior that objects created from the class can have.

class Student:

    name = "Rahul"
    age = 20

The class itself is a blueprint. An object can be created from it.

What is an Object?

An object is an instance of a class. A class can be used to create multiple objects.

class Student:

    name = "Rahul"


student1 = Student()

print(student1.name)

Output:

Rahul

Class and Object Example

class Student:

    name = "Rahul"
    course = "Python"


student1 = Student()

print(student1.name)
print(student1.course)

Output:

Rahul
Python

The __init__() Method

The __init__() method is a special method that is commonly used to initialize object data when an object is created.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student1 = Student("Rahul", 20)

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

Output:

Rahul
20

The self Parameter

The self parameter refers to the current object. It is used to access variables and methods belonging to that object.

class Student:

    def __init__(self, name):

        self.name = name


student1 = Student("Rahul")

print(student1.name)

Methods in a Class

A method is a function defined inside a class. Methods describe behavior associated with objects.

class Student:

    def __init__(self, name):

        self.name = name


    def display(self):

        print("Student Name:", self.name)


student1 = Student("Rahul")

student1.display()

Output:

Student Name: Rahul

Creating Multiple Objects

One class can be used to create many objects. Each object can contain different data.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student1 = Student("Rahul", 20)

student2 = Student("Amit", 22)

print(student1.name)
print(student2.name)

Output:

Rahul
Amit

Instance Variables

Instance variables are variables that belong to a particular object. They are usually created using self.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age

Here, name and age are instance variables. Each object can have different values.

Class Variables

A class variable belongs to the class and is shared by instances unless an instance provides its own value.

class Student:

    school = "Soopro Pathshala"


student1 = Student()
student2 = Student()

print(student1.school)
print(student2.school)

Output:

Soopro Pathshala
Soopro Pathshala

Instance Variable vs Class Variable

Instance Variable Class Variable
Belongs to an individual object Belongs to the class
Usually created using self Defined directly inside the class
Can have different values for each object Can be shared by objects

Encapsulation

Encapsulation means keeping data and the methods that operate on that data together inside a class. Python also provides naming conventions and name mangling for restricting direct access to some attributes.

class BankAccount:

    def __init__(self, balance):

        self.__balance = balance


    def get_balance(self):

        return self.__balance


account = BankAccount(5000)

print(account.get_balance())

Output:

5000

Inheritance

Inheritance allows one class to derive or inherit attributes and methods from another class.

class Animal:

    def speak(self):

        print("Animal makes a sound")


class Dog(Animal):

    pass


dog = Dog()

dog.speak()

Output:

Animal makes a sound

Polymorphism

Polymorphism means that the same method or operation can behave differently depending on the object or context.

class Dog:

    def sound(self):

        print("Bark")


class Cat:

    def sound(self):

        print("Meow")


animals = [Dog(), Cat()]

for animal in animals:

    animal.sound()

Output:

Bark
Meow

Abstraction

Abstraction means exposing the necessary interface while hiding implementation details. Python supports abstraction using the abc module.

from abc import ABC, abstractmethod


class Animal(ABC):

    @abstractmethod
    def sound(self):
        pass


class Dog(Animal):

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


dog = Dog()

dog.sound()

Output:

Bark

Constructor

A constructor is commonly represented by the __init__() method in Python. It runs automatically when an object is initialized.

class Employee:

    def __init__(self, name):

        self.name = name


employee = Employee("Rahul")

print(employee.name)

Output:

Rahul

Destructor

Python provides the special method __del__(), which may be called when an object is about to be finalized. It should not be relied upon for critical resource cleanup.

class Student:

    def __del__(self):

        print("Object finalized")


student = Student()

For files, database connections, and similar resources, use context managers such as with instead of relying on __del__().

Types of Methods

Python classes commonly use three types of methods:

  • Instance Method – works with an object instance.
  • Class Method – works with the class using @classmethod.
  • Static Method – does not require an instance or class state and uses @staticmethod.
class Student:

    school = "Soopro Pathshala"


    def display(self):

        print("Instance Method")


    @classmethod
    def show_school(cls):

        print(cls.school)


    @staticmethod
    def welcome():

        print("Welcome")


student = Student()

student.display()

Student.show_school()

Student.welcome()

Class Method

A class method uses the @classmethod decorator. It receives the class as its first parameter, conventionally named cls.

class Student:

    school = "Soopro Pathshala"


    @classmethod
    def show_school(cls):

        print(cls.school)


Student.show_school()

Output:

Soopro Pathshala

Static Method

A static method uses the @staticmethod decorator. It does not receive self or cls automatically.

class Calculator:

    @staticmethod
    def add(a, b):

        return a + b


print(Calculator.add(10, 20))

Output:

30

Multiple Inheritance

Python allows a class to inherit from more than one parent class. This is called multiple inheritance.

class Father:

    def skill1(self):

        print("Driving")


class Mother:

    def skill2(self):

        print("Cooking")


class Child(Father, Mother):

    pass


child = Child()

child.skill1()
child.skill2()

Output:

Driving
Cooking

The super() Function

The super() function can be used to call methods or access behavior from a parent class.

class Animal:

    def __init__(self, name):

        self.name = name


class Dog(Animal):

    def __init__(self, name, breed):

        super().__init__(name)

        self.breed = breed


dog = Dog("Tommy", "Labrador")

print(dog.name)
print(dog.breed)

Output:

Tommy
Labrador

Why Use OOP?

  • Helps organize large programs.
  • Promotes code reuse.
  • Makes code easier to maintain.
  • Helps model real-world entities.
  • Supports encapsulation.
  • Supports inheritance.
  • Supports polymorphism.
  • Supports abstraction.

Real-World Example of OOP

Consider a school management system. We can create classes such as:

Student
Teacher
Course
Attendance
Fee
Exam

Each class can contain its own data and methods. For example, a Student class might contain name, age, course, and methods for displaying student information.

Complete OOP Example

class Student:

    school = "Soopro Pathshala"


    def __init__(self, name, age, course):

        self.name = name
        self.age = age
        self.course = course


    def display(self):

        print("Name:", self.name)
        print("Age:", self.age)
        print("Course:", self.course)
        print("School:", Student.school)


student1 = Student(
    "Rahul",
    20,
    "Python"
)

student1.display()

Output:

Name: Rahul
Age: 20
Course: Python
School: Soopro Pathshala

Four Main Concepts of OOP

Concept Meaning
Encapsulation Combines data and methods and controls access to data.
Inheritance Allows a class to reuse behavior from another class.
Polymorphism Allows the same interface or method name to behave differently.
Abstraction Exposes essential behavior while hiding implementation details.

Key Points

  • OOP stands for Object Oriented Programming.
  • A class is a blueprint for creating objects.
  • An object is an instance of a class.
  • The __init__() method is commonly used to initialize object data.
  • The self parameter refers to the current object.
  • Methods are functions defined inside a class.
  • Python supports inheritance and multiple inheritance.
  • super() can be used to work with parent-class behavior.
  • Python supports encapsulation, inheritance, polymorphism, and abstraction.
  • OOP helps organize and reuse code in larger applications.

🧠 Quick Quiz

Question: What is a class in Python?