- 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
Add to BookmarkWhat 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
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- How to Start Your Career as a DevOps Engineer
- Career Guide: Natural Language Processing (NLP)
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- SQL Joins Explained: A Complete Guide with Examples
- 10 Awesome Data Science Blogs To Check Out
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Top 15 Recommended SEO Tools
- Deep Learning (DL): The Core of Modern AI
- Datasets for Speech Recognition Analysis
- Best Platform to Learn Digital Marketing in Free
- Quantum AI – The Future of AI Powered by Quantum Computing
- How AI Companies Are Making Humans Fools and Exploiting Their Data
- The Ultimate Guide to Machine Learning (ML) for Beginners
- The Ultimate Guide to Data Science: Everything You Need to Know
- Transforming Logistics: The Power of AI in Supply Chain Management
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- 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