Constructor Concept in Python

Published Aug. 3, 2023, 1:31 p.m.

In Python, a constructor is a special method that gets called automatically at the time of object creation. The constructor's name should be __init__(self), and its main purpose is to declare and initialize instance variables. If we don't provide a constructor, Python will provide a default constructor.

Example 1: Simple Class with Constructor

Let's create a class Car with a constructor that initializes the make and model attributes.

class Car:
    def __init__(self, make, model):
        # Constructor with `self` and two arguments `make` and `model`
        self.make = make
        self.model = model

    def get_info(self):
        # Method to get car information
        return f"This car is a {self.make} {self.model}."

Now, let's create an instance of the Car class and call the get_info() method.

# Create a car instance using the constructor
car1 = Car("Toyota", "Corolla")

# Call the method to get car information
print(car1.get_info())

Output:

This car is a Toyota Corolla.

Explanation:

  1. We define a class Car with a constructor __init__, which takes three parameters: selfmake, and model. The self parameter is required in all instance methods to refer to the instance itself.

  2. Inside the constructor, we use the self variable to initialize the instance variables make and model. For example, self.make = make assigns the value of the make parameter to the make attribute of the instance.

  3. We define another method called get_info() that uses the self variable to access the instance attributes and returns a formatted string with the car's make and model.

  4. We create an instance of the Car class called car1 by passing the arguments "Toyota" and "Corolla" to the constructor.

  5. We call the get_info() method on the car1 instance, which returns the formatted car information.

Example 2: Class with Default Constructor

If we don't provide any constructor, Python will provide a default constructor for us.

class Student:
    def set_details(self, name, age):
        # Method to set student details
        self.name = name
        self.age = age

    def display_details(self):
        # Method to display student details
        return f"Name: {self.name}, Age: {self.age}"

Now, let's create an instance of the Student class, set the details using the set_details() method, and then display the details using the display_details() method.

# Create a student instance (Python will use the default constructor)
student1 = Student()

# Set the student details using the method
student1.set_details("Alice", 20)

# Display the student details using the method
print(student1.display_details())

Output:

Name: Alice, Age: 20

Explanation:

  1. We define a class Student without providing any constructor. Since we didn't provide a constructor, Python automatically provides a default constructor.

  2. We define two methods: set_details() and display_details(). The set_details() method sets the name and age attributes using the self variable, and the display_details() method displays the student's name and age.

  3. We create an instance of the Student class called student1. Since we didn't provide a constructor, Python uses the default constructor to create the instance.

  4. We call the set_details() method on the student1 instance to set the student's name and age.

  5. We call the display_details() method on the student1 instance to display the student's name and age.

In this example, we see that even without explicitly providing a constructor, Python provides a default constructor that allows us to create instances of the class and set attributes dynamically. However, it is recommended to define a constructor explicitly when you need to initialize instance variables during object creation.

Example 3: Let's create a simple Python program to demonstrate that the constructor will execute only once per object.

class MyClass:
    def __init__(self):
        print("Constructor is executed.")
        self.counter = 0

    def increment_counter(self):
        self.counter += 1

    def get_counter(self):
        return self.counter

# Create instances of the class
obj1 = MyClass()
obj2 = MyClass()

# Call methods on each instance
obj1.increment_counter()
obj1.increment_counter()
obj2.increment_counter()

# Display the counter for each instance
print("Counter for obj1:", obj1.get_counter())
print("Counter for obj2:", obj2.get_counter())

Output:

Constructor is executed.
Constructor is executed.
Counter for obj1: 2
Counter for obj2: 1

Explanation:

  1. We define a class MyClass with a constructor __init__. In the constructor, we print a message "Constructor is executed." and initialize an instance variable counter to 0.

  2. We define two methods: increment_counter() and get_counter(). The increment_counter() method increments the counter attribute, and the get_counter() method returns the value of the counter.

  3. We create two instances of the MyClass class: obj1 and obj2.

  4. When we create each instance, the constructor __init__ is executed once for each object. In this case, the message "Constructor is executed." is printed twice, indicating that the constructor is executed once per object.

  5. We call the increment_counter() method on obj1 twice and on obj2 once.

  6. After calling the methods, we display the values of the counter attribute for each object using the get_counter() method. obj1 has a counter value of 2, and obj2 has a counter value of 1, showing that the counter attribute is separate and maintains its state for each instance.

Differences between Methods and Constructors

Methods:

  • Methods are functions defined within a class to perform specific actions or operations on the class's data (attributes).
  • They are called on instances of the class and can access instance variables using the self parameter.
  • Methods can take additional parameters apart from self to perform their operations.
  • They can return values or perform actions without returning anything.

Constructors:

  • Constructors are special methods in a class that are automatically called when an object is created from the class.
  • The constructor's name is always __init__, and it is used to initialize the object's attributes (instance variables).
  • Constructors are executed only once per object at the time of object creation.
  • They do not have a return type and automatically return None.

Example: Real-Life Scenario

Let's consider a real-life example of a Car class to understand the differences between methods and constructors.

class Car:
    def __init__(self, make, model):
        # Constructor to initialize make and model attributes
        self.make = make
        self.model = model
        self.speed = 0

    def accelerate(self, increment):
        # Method to accelerate the car's speed
        self.speed += increment

    def brake(self, decrement):
        # Method to apply the car's brakes
        if self.speed >= decrement:
            self.speed -= decrement
        else:
            self.speed = 0

    def get_speed(self):
        # Method to retrieve the car's current speed
        return self.speed

In this example, the Car class represents a car object with attributes makemodel, and speed. The __init__ constructor initializes the make and model attributes with the provided values during object creation. The speed attribute is set to 0 by default.

  • accelerate(self, increment): This method takes an increment parameter and increases the car's speed by the specified increment.

  • brake(self, decrement): This method takes a decrement parameter and reduces the car's speed by the specified decrement. If the car's speed becomes negative due to excessive braking, the speed is set to 0.

  • get_speed(self): This method returns the car's current speed.

Usage:

# Create a car instance and initialize its make and model using the constructor
my_car = Car("Toyota", "Corolla")

# Accelerate the car
my_car.accelerate(30)

# Display the current speed using the method
print("Current speed:", my_car.get_speed())  # Output: Current speed: 30

# Apply the brakes to slow down the car
my_car.brake(10)

# Display the current speed again
print("Current speed:", my_car.get_speed())  # Output: Current speed: 20

In this example, we create a car object using the Car class and use the accelerate() and brake() methods to increase and decrease the car's speed. The constructor (__init__) is called only once during the object's creation to set the initial values of make and model. The methods are called multiple times to perform specific actions on the car object.