Python Constructor

A constructor in Python is a special method that initializes the attributes of the object at the time when an object is created. Python uses _init_ for constructor. When a new object of any class is instantiated, this _init_ method automatically gets called.

Key Points About Constructors

  1. Purpose:
    • Initialize the object’s attributes
    • Setup any required operations upon object creation.
  2. Name:
    • The name for the constructor method is always _init_.
    • In Python, this is an inherent method.
  3. Automatic Calling:
    • The _init_ function is called automatically by python when creating a new class instance
  4. First Argument (self):
    • The first parameter of the constructor is self, which is a reference to the current object being created.
    • It allows you to access and modify the attributes of the object.

Syntax of a Constructor

class ClassName:
    def __init__(self, param1, param2):
        self.attribute1 = param1
        self.attribute2 = param2

Example: Using a Constructor

class Person:
    def __init__(self, name, age):
        self.name = name  # Assign name to the object's name attribute
        self.age = age    # Assign age to the object's age attribute
    
    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Create objects of the Person class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Call method to display information
person1.display_info()
person2.display_info()

Output:

Name: Alice, Age: 25
Name: Bob, Age: 30

Types of Constructors

  1. Default Constructor:
    • A constructor without parameters (except self).
    • Used to initialize an object with default values.
class Example:
    def __init__(self):
        self.value = 0

obj = Example()
print(obj.value)  # Output: 0

2. Parameterized Constructor:

  • A constructor that accepts arguments to initialize attributes.
class Example:
    def __init__(self, value):
        self.value = value

obj = Example(42)
print(obj.value)  # Output: 42

Key Notes

  1. Optional Parameters: You can use default argument values to make parameters optional in the constructor.
class Example:
    def __init__(self, value=0):
        self.value = value

obj1 = Example()
obj2 = Example(100)
print(obj1.value)  # Output: 0
print(obj2.value)  # Output: 100

2. Overloading: Python does not support multiple constructors in the traditional sense. But you can still achieve such a behavior using default parameters or by handling arguments dynamically.

class Example:
    def __init__(self, *args):
        if len(args) == 0:
            self.value = 0
        elif len(args) == 1:
            self.value = args[0]

obj1 = Example()
obj2 = Example(42)
print(obj1.value)  # Output: 0
print(obj2.value)  # Output: 42

3. Destructor: While _init_ is for initialisation, the destructor (_del_) is called while an object is destroyed. Nonetheless, it is rarely called in Python since most cleaning is done by garbage collector.

Common Use Cases for Constructors

  1. Encapsulation: Protect data by initializing it within the class.
  2. Polymorphism: Support dynamic initialization depending on the input.
  3. Default Settings: Set up default configurations for an object.