These concepts ensure that Python objects are created and removed in a controlled and predictable way.
What is a Constructor?
A constructor is a special method that is automatically called when an object of a class is created. It's main purpose is to initialize object attributes and perform setup operations.In Python, the constructor is defined using the special method:
__init__(self, ...)
Syntax of a Constructor
class ClassName:
def __init__(self, parameters):
# initialization code
- The method name must be __init__ (with double underscores before and after).- The first parameter is always self, referring to the instance being created.
- You can pass additional parameters to initialize object-specific data.
Example: Parameterized Constructor
class Student:
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
print("Constructor called โ Student object created!")
s1 = Student("Alice", 101)
print(s1.name, s1.roll_no)
Output:
Constructor called โ Student object created!
Alice 101
- Here, __init__() runs automatically when the object s1 is created.- The attributes name and roll_no are initialized with the provided values.
Types of Constructors in Python
Python technically supports one constructor per class, but based on behavior, we can classify constructors as:| Type | Description | Example |
|---|---|---|
| Default Constructor | Does not accept any arguments other than self. |
def __init__(self): ... |
| Parameterized Constructor | Accepts arguments to initialize instance attributes. | def __init__(self, arg1, arg2): ... |
Example 1: Default Constructor
class Employee:
def __init__(self):
self.name = "Unknown"
print("Default constructor called.")
e1 = Employee()
print(e1.name)
Output:
Default constructor called.
Unknown
Example 2: Parameterized Constructor
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
e1 = Employee("John", 50000)
print("Name:", e1.name)
print("Salary:", e1.salary)
Output:
Name: John
Salary: 50000
Example 3: Using Default Arguments in Constructors
You can combine both behaviors using default arguments:class Car:
def __init__(self, brand="Unknown", model="Generic"):
self.brand = brand
self.model = model
c1 = Car()
c2 = Car("Tesla", "Model S")
print(c1.brand, c1.model)
print(c2.brand, c2.model)
Output:
Unknown Generic
Tesla Model S
- This allows creating objects with or without parameters.- It improves flexibility in object initialization.
What is a Destructor?
A destructor is a special method that is automatically called when an object is about to be destroyed. It helps perform cleanup operations, such as closing files, releasing memory, or disconnecting from a database.In Python, the destructor is defined using the special method:
__del__(self)
Example: Destructor in Action
class Demo:
def __init__(self):
print("Constructor called โ Object created!")
def __del__(self):
print("Destructor called โ Object destroyed!")
obj = Demo()
del obj # explicitly deleting the object
Output:
Constructor called โ Object created!
Destructor called โ Object destroyed!
- The destructor __del__() is automatically invoked when the object's reference count becomes zero or when del is used.- In many cases, Python's garbage collector calls destructors automatically when an object is no longer needed.
When Are Destructors Called Automatically?
Python's garbage collector automatically destroys objects when:- The object goes out of scope
- The program ends
- There are no references left to the object
Example:
class Test:
def __init__(self):
print("Object Created")
def __del__(self):
print("Object Destroyed")
def create_object():
obj = Test()
create_object()
print("End of program")
Output:
Object Created
Object Destroyed
End of program
The destructor is called automatically after the function create_object() finishes execution and the object obj goes out of scope.
Constructor and Destructor Together
class FileHandler:
def __init__(self, filename):
self.file = open(filename, "w")
print("File opened successfully!")
def write_data(self, data):
self.file.write(data)
def __del__(self):
self.file.close()
print("File closed successfully!")
f = FileHandler("example.txt")
f.write_data("Python OOP is powerful!")
- Constructor opens the file when the object is created.- Destructor ensures the file is closed properly when the object is destroyed.
Important Notes
- Python's garbage collection system handles most memory cleanup automatically.
- You don't need destructors in every class โ only when working with resources like files or network connections.
- Explicitly calling del removes a reference to the object but doesn't guarantee immediate destruction.
- Destructors might not be called immediately if there are circular references.
Summary
Constructors and destructors form the foundation of object lifecycle management in Python. By defining them properly, you ensure that:
1. Every object starts with a valid state (via constructor).
2. Every object releases its resources properly (via destructor).
Concept
Description
Constructor
Initializes an object when created
Destructor
Cleans up before object destruction
Syntax (Constructor)
def __init__(self, args):
Syntax (Destructor)
def __del__(self):
Triggered Automatically
Yes โ both are called automatically by Python
While constructors are used frequently in most classes, destructors are primarily needed when your objects manage external resources such as files, database connections, or network sockets.
| Concept | Description |
|---|---|
| Constructor | Initializes an object when created |
| Destructor | Cleans up before object destruction |
| Syntax (Constructor) | def __init__(self, args): |
| Syntax (Destructor) | def __del__(self): |
| Triggered Automatically | Yes โ both are called automatically by Python |