In Python, a constructor is a special method used to initialize an object when it is created. This method is called automatically when a new instance of a class is instantiated. Constructors are defined using the init method.

Key Characteristics of Constructors:

  1. Automatic Invocation: The init method is called automatically when an object is created.
  2. Initialization: It is used to initialize the object’s attributes or perform any setup tasks.
  3. Not Mandatory: A class does not require a constructor if there is no need for initialization, but if defined, the constructor ensures proper initialization of attributes.

Constructor Syntax

class MyClass:
    def __init__(self, arg1, arg2):
        self.attribute1 = arg1
        self.attribute2 = arg2

# Create an object of MyClass
obj = MyClass("value1", "value2")

# Access attributes
print(obj.attribute1)  # Output: value1
print(obj.attribute2)  # Output: value2

Types of Constructors

  1. Default Constructor: A constructor that does not take any arguments (except self).

    class MyClass:
        def __init__(self):
            self.name = "Default Name"
    
    obj = MyClass()
    print(obj.name)  # Output: Default Name
    
  2. Parameterized Constructor: A constructor that takes arguments to initialize attributes dynamically.

    class MyClass:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    obj = MyClass("Alice", 25)
    print(obj.name)  # Output: Alice
    print(obj.age)   # Output: 25
    

Example: Constructor in Action

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object of Person
person = Person("John", 30)
person.greet()

Output: Hello, my name is John and I am 30 years old.