In Python, a constructor is a special method used to initialize an object’s state when it is created. Constructors are defined using the __init__() method. This tutorial will explain Python constructors with examples.
What is a Constructor?
A constructor is a method that gets called automatically when an object of a class is created. It is used to initialize the object’s attributes. In Python, there are two types of constructors:
- Default Constructor: A constructor that does not accept any arguments except
self. - Parameterized Constructor: A constructor that accepts arguments to initialize an object with specific values.
1. Default Constructor
A default constructor does not take any parameters (except self) and initializes the object with default values.
Example:
class DefaultConstructorExample:
def __init__(self): # Default constructor
self.message = "This is a default constructor."
def show_message(self):
return self.message
# Create an object
obj = DefaultConstructorExample()
print(obj.show_message()) # Output: This is a default constructor.
2. Parameterized Constructor
A parameterized constructor accepts arguments to initialize object attributes with specific values.
Example:
class ParameterizedConstructorExample:
def __init__(self, name, age): # Parameterized constructor
self.name = name
self.age = age
def display_info(self):
return f"Name: {self.name}, Age: {self.age}"
# Create an object with parameters
person = ParameterizedConstructorExample("Alice", 30)
print(person.display_info()) # Output: Name: Alice, Age: 30
How the __init__() Method Works
The __init__() method is the most commonly used constructor in Python. It is called when an object is created, and it initializes the object’s attributes.
Example:
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def car_details(self):
return f"{self.year} {self.brand} {self.model}"
car1 = Car("Toyota", "Corolla", 2022)
print(car1.car_details()) # Output: 2022 Toyota Corolla
Constructor with Default Values
You can provide default values for constructor parameters, making them optional when creating an object.
Example:
class Book:
def __init__(self, title, author="Unknown"):
self.title = title
self.author = author
def book_info(self):
return f"Title: {self.title}, Author: {self.author}"
book1 = Book("1984", "George Orwell")
book2 = Book("The Alchemist")
print(book1.book_info()) # Output: Title: 1984, Author: George Orwell
print(book2.book_info()) # Output: Title: The Alchemist, Author: Unknown
Constructor Overloading
Python does not support constructor overloading directly (i.e., multiple constructors with different signatures). However, you can simulate it using default arguments or *args and **kwargs.
Example with *args:
class Student:
def __init__(self, *args):
if len(args) == 1:
self.name = args[0]
self.grade = "Not Assigned"
elif len(args) == 2:
self.name = args[0]
self.grade = args[1]
def student_info(self):
return f"Student: {self.name}, Grade: {self.grade}"
student1 = Student("John")
student2 = Student("Jane", "A")
print(student1.student_info()) # Output: Student: John, Grade: Not Assigned
print(student2.student_info()) # Output: Student: Jane, Grade: A
Destructor in Python
A destructor is a special method called __del__(), which is invoked when an object is about to be destroyed. It is used to clean up resources.
Example:
class Sample:
def __init__(self, value):
self.value = value
print(f"Object with value {self.value} created.")
def __del__(self):
print(f"Object with value {self.value} destroyed.")
obj1 = Sample(10)
del obj1 # Manually deleting the object
# Output:
# Object with value 10 created.
# Object with value 10 destroyed.
Conclusion
Constructors are essential for initializing objects and setting their initial state. By understanding default and parameterized constructors, you can write cleaner and more efficient code.