- Object-Oriented Programming (OOP) in Python
-
Overview
- Introduction to OOP in Python
- Classes and Objects
- Constructors (__init__) and Destructors
- Inheritance (Single, Multiple, Multilevel)
- Polymorphism and Method Overriding
- Encapsulation and Data Hiding
- Abstract Classes and Interfaces
- Static and Class Methods
- Magic/Dunder Methods (__str__, __repr__)
- Metaclasses in Python
- Method Resolution Order (MRO) in Python
Constructors (__init__) and Destructors
What is a Constructor?
A constructor is a special method in a class that gets called automatically when a new object is created. In Python, the constructor method is __init__()
.
Defining a Constructor in Python
The __init__()
method is used to initialize an object’s attributes when it is created.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating an object
person1 = Person("Ankit", 25)
person1.greet() # Output: Hello, my name is Ankit and I am 25 years old.
How the Constructor Works
- When
person1 = Person("Ankit", 25)
is executed:__init__()
is called automatically."Ankit"
and25
are assigned toself.name
andself.age
.- The object
person1
is now initialized with these values.
Types of Constructors in Python
Python supports three types of constructors:
1 . Default Constructor (No Parameters except self
)
- A constructor that does not take any arguments except
self
.
class Example:
def __init__(self):
print("Default constructor called")
obj = Example() # Output: Default constructor called
2. Parameterized Constructor
- A constructor that takes arguments to initialize an object’s attributes.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car1 = Car("Tesla", "Model S")
print(car1.brand, car1.model) # Output: Tesla Model S
3. Constructor with Default Values
- You can assign default values to constructor parameters.
class Laptop:
def __init__(self, brand="Dell"):
self.brand = brand
l1 = Laptop()
l2 = Laptop("HP")
print(l1.brand) # Output: Dell
print(l2.brand) # Output: HP
What is a Destructor?
A destructor is a special method that is called when an object is deleted or goes out of scope. In Python, the destructor method is __del__()
.
Defining a Destructor in Python
class Student:
def __init__(self, name):
self.name = name
print(f"Student {self.name} created!")
def __del__(self):
print(f"Student {self.name} is being deleted.")
# Creating an object
s1 = Student("Vivek")
# Deleting the object manually
del s1 # Output: Student Vivek is being deleted.
When is the Destructor Called?
- It is called automatically when an object is no longer in use.
- If the object is explicitly deleted using
del
, the destructor is executed immediately. - If an object goes out of scope (e.g., at the end of a function), the destructor is called.
def create_student():
s2 = Student("Akash")
print("Inside function")
create_student()
print("Outside function")
# Output:
# Student Akash created!
# Inside function
# Student Emma is being deleted.
# Outside function
Summary
The constructor (__init__()
) is called when an object is created.
Types of constructors: Default, Parameterized, and with Default Values.
The destructor (__del__()
) is called when an object is deleted or goes out of scope.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- Important Mistakes to Avoid While Advertising on Facebook
- Datasets for analyze in Tableau
- 15 Amazing Keyword Research Tools You Should Explore
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Understanding HTAP Databases: Bridging Transactions and Analytics
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Variable Assignment in Python
- What is YII? and How to Install it?
- Extract RGB Color From a Image Using CV2
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Generative AI - The Future of Artificial Intelligence
- Convert RBG Image to Gray Scale Image Using CV2
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset