Python Constructors: Initializing Class Instances

Understand Python constructors and how they are used to initialize instance variables in a class. Learn about the __init__() method, which is automatically called when a new object is created, and how it helps set up object properties.



Python - Constructors

A constructor in Python is an instance method in a class that is automatically called whenever a new object of the class is created. Its role is to initialize instance variables for the object.

Creating a Constructor in Python

Python uses the __init__() method to initialize instance variables as soon as the object is created. This method takes a mandatory argument named self, which is a reference to the object.

Syntax

def __init__(self, parameters):
    # initialize instance variables
        

Types of Constructors in Python

Python has two types of constructors:

  • Default Constructor
  • Parameterized Constructor

Default Constructor

A default constructor does not accept any parameters other than self.

Example

class Employee:
    'Common base class for all employees'
    def __init__(self):
        self.name = "Aditi"
        self.age = 24

e1 = Employee()
print("Name: {}".format(e1.name))
print("Age: {}".format(e1.age))
        
Output

Name: Aditi
Age: 24
        

Parameterized Constructor

A parameterized constructor accepts multiple parameters along with self.

Example

class Employee:
    'Common base class for all employees'
    def __init__(self, name, age):
        self.name = name
        self.age = age

e1 = Employee("Aditi", 24)
e2 = Employee("Bharat", 25)

print("Name: {}".format(e1.name))
print("Age: {}".format(e1.age))
print("Name: {}".format(e2.name))
print("Age: {}".format(e2.age))
        
Output

Name: Aditi
Age: 24
Name: Bharat
Age: 25
        

Default Values in Parameterized Constructor

You can assign default values to the formal arguments in the constructor.

Example

class Employee:
    'Common base class for all employees'
    def __init__(self, name="Aditi", age=24):
        self.name = name
        self.age = age

e1 = Employee()
e2 = Employee("Bharat", 25)

print("Name: {}".format(e1.name))
print("Age: {}".format(e1.age))
print("Name: {}".format(e2.name))
print("Age: {}".format(e2.age))
        
Output

Name: Aditi
Age: 24
Name: Bharat
Age: 25
        

Python Multiple Constructors

Python does not support multiple constructors directly. However, we can achieve similar functionality using default arguments or variable length arguments.

Example

class Student:
    def __init__(self, *args):
        if len(args) == 1:
            self.name = args[0]
        
        elif len(args) == 2:
            self.name = args[0]
            self.age = args[1]
        
        elif len(args) == 3:
            self.name = args[0]
            self.age = args[1]
            self.gender = args[2]

st1 = Student("Shrey")
print("Name:", st1.name)
st2 = Student("Ram", 25)
print(f"Name: {st2.name} and Age: {st2.age}")
st3 = Student("Shyam", 26, "M")
print(f"Name: {st3.name}, Age: {st3.age} and Gender: {st3.gender}")
        
Output

Name: Shrey
Name: Ram and Age: 25
Name: Shyam, Age: 26 and Gender: M