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.
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()
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.
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 Student:
name = "Rahul"
course = "Python"
student1 = Student()
print(student1.name)
print(student1.course)
Output:
Rahul Python
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 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)
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
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 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.
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 | 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 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 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 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 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
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
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__().
Python classes commonly use three types of methods:
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()
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
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
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 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
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.
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
| 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. |
Question: What is a class in Python?