Lesson 51 of 70 – Python Constructor
73%

Python Constructor

A constructor is a special method that is commonly used to initialize an object when it is created. In Python, the __init__() method is normally used for this purpose.

Note: The __init__() method is automatically called when an object is initialized from a class.

What is a Constructor?

A constructor is a method used to initialize the attributes of an object. It allows us to provide initial values when creating an object.

class Student:

    def __init__(self):

        print("Constructor called")


student = Student()

Output:

Constructor called

The __init__() Method

The __init__() method is a special instance method commonly used to initialize object attributes.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student = Student("Rahul", 20)

print(student.name)
print(student.age)

Output:

Rahul
20

Constructor is Called Automatically

When an object is created, Python automatically calls the __init__() method after the new instance has been created.

class Student:

    def __init__(self):

        print("Student object initialized")


student = Student()

Output:

Student object initialized

Constructor and self

The first parameter of an instance method is conventionally named self. It refers to the current object.

class Student:

    def __init__(self, name):

        self.name = name


student = Student("Rahul")

print(student.name)

Here, self.name stores the name inside the object.

Constructor with Parameters

A constructor can accept parameters so that each object can be initialized with different values.

class Employee:

    def __init__(self, name, salary):

        self.name = name
        self.salary = salary


employee = Employee("Rahul", 30000)

print(employee.name)
print(employee.salary)

Output:

Rahul
30000

Constructor with Multiple Objects

The same constructor can initialize different objects with different values.

class Student:

    def __init__(self, name, age):

        self.name = name
        self.age = age


student1 = Student("Rahul", 20)

student2 = Student("Amit", 22)

student3 = Student("Priya", 21)

print(student1.name)
print(student2.name)
print(student3.name)

Output:

Rahul
Amit
Priya

Constructor with Default Values

Constructor parameters can have default values. This allows an object to be created without providing every argument.

class Student:

    def __init__(self, name, course="Python"):

        self.name = name
        self.course = course


student1 = Student("Rahul")

student2 = Student("Amit", "Java")

print(student1.name, student1.course)

print(student2.name, student2.course)

Output:

Rahul Python
Amit Java

Validating Data in a Constructor

A constructor can validate data before storing it in an object.

class Student:

    def __init__(self, name, age):

        if age >= 18:

            self.name = name
            self.age = age

        else:

            raise ValueError(
                "Age must be 18 or above"
            )


student = Student("Rahul", 20)

print(student.name)

Output:

Rahul

Constructor with Methods

A class can contain a constructor as well as other methods.

class Student:

    def __init__(self, name, course):

        self.name = name
        self.course = course


    def display(self):

        print("Name:", self.name)
        print("Course:", self.course)


student = Student(
    "Rahul",
    "Python"
)

student.display()

Output:

Name: Rahul
Course: Python

Constructor with Class Variables

A constructor can initialize instance variables while the class can also contain class variables shared by instances.

class Student:

    school = "Soopro Pathshala"


    def __init__(self, name):

        self.name = name


student = Student("Rahul")

print(student.name)
print(student.school)

Output:

Rahul
Soopro Pathshala

Constructor and Inheritance

When a child class defines its own __init__(), the parent's initializer is not automatically called. The child can explicitly call the parent initializer using super().

class Person:

    def __init__(self, name):

        self.name = name


class Student(Person):

    def __init__(self, name, course):

        super().__init__(name)

        self.course = course


student = Student("Rahul", "Python")

print(student.name)
print(student.course)

Output:

Rahul
Python

Using super() in Constructor

The super() function is useful when a child class needs to reuse initialization logic from its parent class.

class Animal:

    def __init__(self, name):

        self.name = name


class Dog(Animal):

    def __init__(self, name, breed):

        super().__init__(name)

        self.breed = breed


dog = Dog("Tommy", "Labrador")

print(dog.name)
print(dog.breed)

Output:

Tommy
Labrador

Class Without __init__()

A class does not have to define its own __init__() method. Python can still create instances of the class.

class Student:

    def display(self):

        print("Student")


student = Student()

student.display()

Output:

Student

Empty Constructor

An initializer can contain only pass if there is currently no initialization logic to perform.

class Student:

    def __init__(self):

        pass


student = Student()

print("Object created")

Output:

Object created

Constructor with Multiple Parameters

A constructor can accept many parameters to initialize a complete object.

class Employee:

    def __init__(
        self,
        name,
        age,
        department,
        salary
    ):

        self.name = name
        self.age = age
        self.department = department
        self.salary = salary


employee = Employee(
    "Rahul",
    25,
    "IT",
    40000
)

print(employee.name)
print(employee.department)
print(employee.salary)

Output:

Rahul
IT
40000

Constructor with Keyword Arguments

Constructor arguments can be passed using parameter names.

class Student:

    def __init__(self, name, age, course):

        self.name = name
        self.age = age
        self.course = course


student = Student(
    name="Rahul",
    age=20,
    course="Python"
)

print(student.name)
print(student.course)

Output:

Rahul
Python

Be Careful with Mutable Default Values

Using a mutable object such as a list as a default constructor argument can cause unexpected sharing between instances. A safer approach is to use None and create a new list inside the constructor.

class Student:

    def __init__(self, name, subjects=None):

        self.name = name

        if subjects is None:

            subjects = []

        self.subjects = subjects

Constructor and dataclasses

For classes that mainly store data, Python's dataclasses module can automatically generate an initializer and other useful methods.

from dataclasses import dataclass


@dataclass
class Student:

    name: str
    age: int


student = Student("Rahul", 20)

print(student)

Output:

Student(name='Rahul', age=20)

Constructor vs Normal Method

Constructor Normal Method
Commonly written as __init__() Can have any valid method name
Used to initialize an object Used to perform a specific operation
Called automatically during initialization Usually called explicitly
Runs as part of object creation Runs when the method is invoked

Practical Example – Bank Account

A constructor can initialize a bank account with an account holder and an opening balance.

class BankAccount:

    def __init__(self, name, balance):

        self.name = name
        self.balance = balance


    def show_balance(self):

        print("Account Holder:", self.name)
        print("Balance:", self.balance)


account = BankAccount(
    "Rahul",
    5000
)

account.show_balance()

Output:

Account Holder: Rahul
Balance: 5000

Complete Constructor Example

class Student:

    school = "Soopro Pathshala"


    def __init__(
        self,
        name,
        age,
        course
    ):

        self.name = name
        self.age = age
        self.course = course


    def display(self):

        print("Name:", self.name)
        print("Age:", self.age)
        print("Course:", self.course)
        print("School:", self.school)


student1 = Student(
    "Rahul",
    20,
    "Python"
)

student2 = Student(
    "Amit",
    22,
    "Java"
)


student1.display()

print()

student2.display()

Output:

Name: Rahul
Age: 20
Course: Python
School: Soopro Pathshala

Name: Amit
Age: 22
Course: Java
School: Soopro Pathshala

Key Points

  • A constructor is commonly implemented using the __init__() method.
  • The initializer runs automatically when an object is created.
  • The self parameter refers to the current object.
  • Constructor parameters can be used to initialize object attributes.
  • Different objects can receive different constructor values.
  • Constructor parameters can have default values.
  • A child class can call its parent's initializer using super().
  • A class does not have to define its own __init__() method.
  • Validation can be performed during object initialization.
  • Avoid mutable default arguments such as []; use None when appropriate.
  • Python's dataclasses module can generate an initializer for data-focused classes.

🧠 Quick Quiz

Question: Which special method is commonly used as a constructor in Python?