Python Constructor

In Python, a constructor is a special method used to initialize an object's instance members when the object is created. It is typically defined using the __init__ method. Constructors are crucial for setting up the initial state of an object.

Types of Constructors

1. Non-Parameterized Constructor

2. Parameterized Constructor

Non-Parameterized Constructor

A non-parameterized constructor does not take any arguments other than self. It is used when you want to initialize an object with default values.

Example:

class Employee:
    def __init__(self):
        self.name = "Unknown"
        self.age = 0

# Creating an object of Employee
emp = Employee()
print(emp.name)     # Output: Unknown
print(emp.age)     # Output: 0

Parameterized Constructor

A parameterized constructor takes one or more arguments in addition to self. It allows you to initialize an object with specific values.

Example:

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

# Creating an object of Employee with parameters
emp = Employee("John", 30)
print(emp.name)     # Output: John
print(emp.age)     # Output: 30

Default Constructor

If you do not explicitly define a constructor in a class, Python provides a default constructor. This default constructor initializes the object but does not perform any additional tasks.

Example:

class Employee:
    pass

# Creating an object of Employee
emp = Employee()
print(emp)     # Output: <__main__.Employee object at 0x...>

Multiple Constructors

Python does not support method overloading directly. Thus, you cannot have multiple constructors with different signatures in the same class. However, you can simulate this behavior by using default arguments or handling arguments within a single constructor.

Example:

class Employee:
    def __init__(self, name=None, age=None):
        if name is None and age is None:
            self.name = "Unknown"
            self.age = 0
        elif name is not None and age is not None:
            self.name = name
            self.age = age
        else:
            raise ValueError("Invalid arguments provided")

# Creating objects with different constructors
emp1 = Employee()
emp2 = Employee("John", 30)

print(emp1.name, emp1.age)     # Output: Unknown 0
print(emp2.name, emp2.age)     # Output: John 30

Python Built-in Class Functions

Python provides several built-in functions that are used to interact with class attributes and methods:

1. getattr(obj, name, default): Retrieves the value of the attribute name from the object obj. If the attribute does not exist, it returns the default value.

2. setattr(obj, name, value): Sets the value of the attribute name in the object obj to value.

3. delattr(obj, name): Deletes the attribute name from the object obj.

4. hasattr(obj, name):Checks if the object obj has an attribute name. Returns True if it exists, otherwise False.