
Object-Oriented Programming (OOP)s in Python:
OOPs in Python stands for Object-Oriented Programming is a style of coding that revolves around the ideas of objects -these represent real-world elements. Each object can contain both data (attributes) and functions (methods) that operate on the data.
By using OOPs in Python, you can break down into smaller, reusable code, manageable parts by creating, making your code program more organized and scalable.
Benefits of OOP in Python
-
Modularity: Your program is neatly divided into classes and objects.
-
Reusability: You can use the same classes in different projects.
-
Scalability: It’s Easy to extend your program using features like inheritance and polymorphism.
-
Security: Data is protected and hidden through encapsulation.
-
Maintainability: Code is easier to debug, test, and update.
OOPs in Python is based on Four Pillars:
| Pillar | Description |
|---|---|
| 1. Encapsulation | Binding data and methods together in one unit (class). |
| 2. Abstraction | Hiding internal details and showing only relevant info. |
| 3. Inheritance | One class inherits properties of another. |
| 4. Polymorphism | One task performed in different ways. |
OOPs in Python with Classes:
A class is like a blueprint, a design, or a mold for creating objects.
Think of a class like a “Car Design.” It tells you how the car should be structured: how many wheels, the engine type, color options, etc. But a class itself is not a car—it’s just a plan.
In code, a class defines:
-
What attributes (data) each object will have
-
What behaviors (methods/functions) each object can perform
Syntax
class ClassName :def __init_ (self, parameters):
# initialize attributes
def method(self):
# define behavior
OOPs in python for Objects:
An object is an actual “thing” created using the class blueprint.
If the class is the design of a car, then the object is a real car you can drive. You can create multiple objects (cars) from the same class (car design), each with its own data.
python object_name = ClassName(arguments)
Example: Creating a Class and Object in Python
Let’s create a class named Student that represents a student’s name and marks.
python class Student:def __init__ (self, name, marks):self.name = name self. Marks = marks
def show details(self): print (f”Name: {self.name}, Marks: {self.marks}”)
# Creating objects
student1 = Student (“Amit”, 90)
student2 = Student (“Neha”, 85)
student1.show_details ()
student2.show_details ()
Output:
Name: Amit, Marks: 90
Name: Neha, Marks: 85
Here:
-
Student is the class.
-
student1 and student2 are objects.
show_details() is a method that prints data stored in the object
Inheritance in OOPs in Python:
Inheritance is the process by which one class (called the child or derived class) inherits the attributes and methods of another class (called the parent or base class).
It allows us to reuse code from an existing class without rewriting it.
Think of it like this:
-
A child inherits features (eyes, height, surname) from their parents.
-
A university student inherits general human characteristics but also has student-specific behaviors.
In programming terms, the child class can:
-
Access everything from the parent class
-
Add new features
-
Override (modify) inherited features
Syntax
python class Parent:class Child(Parent):# child class members# parent class members
Example: Single Inheritance
Let’s understand with a simple example:
python class Dog(Animal): # Dog inherits from Animalclass Animal:
def speak(self):
print("Animals make sound")
def bark(self):
print(“Dog barks”)d = Dog()
d.speak() # inherited from Animal
d.bark() # defined in Dog
Output:
go Animals make soundDog barks
Explanation:
-
Animal is the parent class.
-
Dog is the child class that inherited speak() from Animal.
Types of Inheritance in Python
| Type | Description | Syntax Example |
|---|---|---|
| Single | One child, one parent | class A → class B(A) |
| Multilevel | Parent → Child → Grandchild | class A → B(A) → C(B) |
| Multiple | One child, multiple parents | class A, B → class C(A, B) |
| Hierarchical | One parent, many children | class A → class B(A), C(A) |
| Hybrid | Combination of multiple types | Complex combinations |
Example: Multilevel Inheritance
python class Grandparent:def show_grandparent(self):class Parent(Grandparent):def show_parent(self):print("I am Grandparent")
print(“I am Parent”)class Child(Parent):
def show_child(self):
print(“I am Child”)c = Child()
c.show_grandparent()
c.show_parent()
c.show_child()
Output:
I am GrandparentI am ParentI am Child
Child inherits everything from both Parent and Grandparent.
Example: Multiple Inheritance
python class Mother:class Father:
def skills(self):
print("Driving, Cooking")
def skills(self):
print(“Painting, Dancing”)class Child(Father, Mother):
def skills(self):
print(“Gaming, Coding”)c = Child()
c.skills()
Output:
Gaming, Coding
If child defines the same method as parents, the child’s version overrides it.
Polymorphism in OOPs in python:
In simple terms, polymorphism means “many forms”. It allows different objects to respond to the same method in different ways.
Types of Polymorphism in Python
Python supports two main types of polymorphism:
-
Duck Typing (Dynamic Typing / Informal Polymorphism)
-
Method Overriding (Formal Polymorphism using Inheritance)
1. Duck Typing (Informal Polymorphism)
In Python, what matters is not the type of an object but whether it implements the needed behavior (i.e., the required methods or properties). This concept is called duck typing:
“If it walks like a duck and quacks like a duck, it’s a duck.”
Example:
python class Cat:def sound(self):class Dog:def sound(self):return "Meow"
return “Woof”def make_sound(animal):
print(animal.sound())cat = Cat()
dog = Dog()make_sound(cat) # Output: Meow
make_sound(dog) # Output: Woof
Here, the make_sound function accepts any object that has a sound() method — it doesn’t care about the actual class.
2. Method Overriding (Formal Polymorphism)
This is achieved through inheritance. When a child class provides a specific implementation of a method that is already defined in its parent class, it overrides the parent class method.
Example:
python class Animal:def speak(self):class Dog(Animal):def speak(self):return "Some sound"
return “Bark”class Cat(Animal):
def speak(self):
return “Meow”animals = [Dog(), Cat()]for animal in animals:
print(animal.speak())
Output:
Bark
Meow
Benefits
-
Code reusability: Common interfaces work with different object types.
-
Scalability: New classes can be added with minimal changes.
-
Clean, readable code: Reduces code duplication.
“OOPs in Python: Encapsulation Explained”
-
It hides the internal state of an object from the outside world.
-
It allows controlled access using public methods (getters/setters).
-
It enhances data protection and security.
Access Modifiers in Python
| Modifier | Syntax | Description |
|---|---|---|
| Public | variable | Accessible from anywhere |
| Protected | _variable | Shouldn’t be accessed outside class (by convention) |
| Private | __variable | Name mangled to prevent direct access |
Example
python class BankAccount:def __init__(self, balance):def deposit(self, amount):if amount > 0:self.__balance = balance # private variable
self.__balance += amountdef withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print(“Insufficient funds.”)def get_balance(self):
return self.__balanceaa
Uses-
-
Hides sensitive data from outside access
-
Protects variables from accidental modification
-
Allows controlled access using getters and setters
-
Validates data before updating variables
“Learn more from the official Python documentation.”
“Also read our Python Functions Guide.
