Constructors in Python
In Python, a constructor is a special method used to initialize objects of a class. It is automatically called when a new object of the class is created. Constructors allow us to set up initial values for object attributes, making sure that objects start with the necessary data.
Syntax
class ClassName:
def __init__(self, parameters):
# Constructor body
Types of Constructors
Constructor Type | Description |
---|---|
Default Constructor | A constructor that takes no parameters except self . |
Parameterized Constructor | A constructor that takes additional parameters to initialize object attributes. |
Constructor with Default Values | A constructor where some or all parameters have default values. |
Examples
1. Default Constructor
A default constructor does not take any parameters other than self
. It initializes every object with predefined values.
In the following example, we define a class Animal
with a default constructor. The constructor prints a message when an object is created.
class Animal:
def __init__(self):
# Constructor with no parameters
print("An animal has been created.")
# Creating an object of the Animal class
a = Animal()
Output:
An animal has been created.
Whenever we create an object of Animal
, the constructor runs automatically and prints a message.
2. Parameterized Constructor
A parameterized constructor takes arguments to initialize instance variables. This allows us to create objects with different values.
In the following example, we define a class Person
with a constructor that accepts a name and age as arguments. The constructor initializes the object’s attributes with these values.
class Person:
def __init__(self, name, age):
# Initializing instance variables
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating an object with specific values
p1 = Person("Arjun", 25)
p1.display()
Output:
Name: Arjun, Age: 25
Here, the constructor initializes self.name
and self.age
with values provided, Arjun
and 25
respectively, while creating the object. When we call display()
, it prints the stored values.
3. Constructor with Default Values
We can assign default values to constructor parameters, so if an argument is not provided, the default value is used.
In the example below, the Car
class has a constructor with default values for brand
and year
. If no values are provided, the defaults are used.
class Car:
def __init__(self, brand="Toyota", year=2020):
self.brand = brand
self.year = year
def show_info(self):
print(f"Brand: {self.brand}, Year: {self.year}")
# Object with default values
c1 = Car()
c1.show_info()
# Object with custom values
c2 = Car("Honda", 2022)
c2.show_info()
Output:
Brand: Toyota, Year: 2020
Brand: Honda, Year: 2022
When we create c1
without arguments, the default values are used. For c2
, we provide custom values that override the defaults.
4. Handling Errors in Constructors
If we forget to pass required arguments to a parameterized constructor, Python raises a TypeError
. Let’s see how this happens and how to handle it.
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
try:
# Forgetting to pass required arguments
s1 = Student("Arjun")
except TypeError as e:
print("Error:", e)
Output:
Error: __init__() missing 1 required positional argument: 'grade'
Python expects two arguments, but only one was given. To prevent such errors, we can provide default values or handle exceptions as shown in the corrected version below.
class Student:
def __init__(self, name, grade="Not Assigned"):
self.name = name
self.grade = grade
# Now it works even if we don't pass the grade
s1 = Student("Ram")
print(f"Name: {s1.name}, Grade: {s1.grade}")
Output:
Name: Ram, Grade: Not Assigned
Now, if the grade
is missing, the default value “Not Assigned”
is used, preventing errors.