Python Constructors

In Python, a constructor is a special type of method that is automatically called when an object of a class is created. Constructors are used to initialize the attributes of a class when an object is instantiated. In other words, constructors allow you to set up the initial state of an object.

What is a Constructor?

A constructor is a function defined within a class using the special method name __init__(). The __init__() method is a reserved method in Python, meaning it has a special meaning and is automatically executed when a new object is created.

The purpose of a constructor is to ensure that an object is properly set up and ready to use. It helps in assigning initial values to the attributes of the object and can perform any setup required before the object is used.

Types of Constructors

In Python, there are two main types of constructors:

How to Define a Constructor in Python?

A constructor is defined using the __init__() method inside a class. The self parameter is a reference to the current instance of the class and is used to access variables and methods associated with the class.

Parameterized Constructor


# Defining a class with a parameterized constructor
class Student:
    # Constructor with parameters
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

    # Method to display student details
    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}, Major: {self.major}")

# Creating objects of the Student class
student1 = Student("Alice", 19, "Computer Science")
student2 = Student("Bob", 21, "Mechanical Engineering")

# Accessing object attributes and methods
student1.display_info()  # Output: Name: Alice, Age: 19, Major: Computer Science
student2.display_info()  # Output: Name: Bob, Age: 21, Major: Mechanical Engineering
            

Output

Name: Alice, Age: 19, Major: Computer Science Name: Bob, Age: 21, Major: Mechanical Engineering

Explanation of Code Example

In this example:
- We defined a class named Student with a parameterized constructor __init__() that takes three arguments: name, age, and major.
- The attributes of each object are set to the values passed as arguments when creating the object.
- We created two objects, student1 and student2, each with different values for the attributes.
- The display_info() method is called to print the details of each student.

Default Constructor


# Defining a class with a default constructor
class Animal:
    # Default constructor
    def __init__(self):
        self.species = "Unknown"
        self.legs = 4

    # Method to display animal details
    def display_info(self):
        print(f"Species: {self.species}, Legs: {self.legs}")

# Creating an object of the Animal class
animal1 = Animal()

# Accessing object attributes and methods
animal1.display_info()  # Output: Species: Unknown, Legs: 4
            

Output

Species: Unknown, Legs: 4

Key Points to Remember

Why Use Constructors?

Constructors are essential in Object-Oriented Programming (OOP) because they allow for:

Advantages of Using Constructors

Understanding constructors is a fundamental aspect of learning Object-Oriented Programming in Python. Constructors help in setting up the initial state of an object, making your code more reliable and easier to understand. By mastering constructors, you'll be able to create classes that are more versatile, efficient, and robust.