Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Constructors in Python

Learn how constructors initialize objects in Python with simple examples and practical programs.

What is a Constructor?

A constructor is a special method that is used to initialize an object when the object is created.

In Python, the method commonly used for initialization is __init__().

It runs automatically when we create an object from a class.

Simple Definition: A constructor gives initial values to an object when the object is created.

Why Do We Use Constructors?

Suppose we create a Student object. We may want to give the student a name, age and course immediately.

A constructor allows us to initialize these values automatically.

  • Initialize object data.
  • Reduce repeated code.
  • Create objects with ready-to-use values.
  • Make object creation easier and cleaner.

Constructor Syntax

The basic syntax of a constructor is:

class ClassName:

    def __init__(self):
        # initialization code

Important points:

  • Constructor is written using __init__().
  • It is written inside the class.
  • The first parameter is usually self.
  • It runs automatically when an object is created.

How Does a Constructor Work?

When we create an object, Python automatically calls the __init__() method.

class Student:

    def __init__(self):
        print("Student object created")


student1 = Student()

Output:

Student object created

When Student() is executed, Python automatically calls __init__().

Types of Constructors in Python

At the beginner level, we commonly discuss these constructor forms:

Constructors

__init__() is used to initialize an object.

↓
1. Default

No extra values are passed while creating the object.

2. Parameterized

Values are passed while creating the object.

3. Default Arguments

Parameters have predefined default values.

1. Default / Non-Parameterized Constructor

A default or non-parameterized constructor does not take extra values from the user when the object is created.

It can be used when every object starts with the same initial information.

Example

class Student:

    def __init__(self):
        self.name = "Sam"
        self.course = "Python"


student1 = Student()

print(student1.name)
print(student1.course)

Output:

Sam
Python

Here, we do not pass any values while creating Student().

The constructor automatically gives the object the values defined inside __init__().

Another Example

class Company:

    def __init__(self):
        self.company_name = "CIIT Training Institute 📩🤓...!"
        self.location = "Pune"


company1 = Company()

print(company1.company_name)
print(company1.location)

Output:

CIIT Training Institute 📩🤓...!
Pune

This is useful when the initial values are fixed or do not need to be supplied during object creation.

2. Parameterized Constructor

A parameterized constructor accepts values while creating the object.

This is useful when each object needs different information.

Example

class Student:

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


student1 = Student("Omkar", 25)

print(student1.name)
print(student1.age)

Output:

Omkar
25

Here, Omkar and 25 are passed while creating the object.

Multiple Objects with Parameterized Constructor

We can create multiple objects with different values using the same constructor.

class Student:

    def __init__(self, name, course):
        self.name = name
        self.course = course


student1 = Student("Samadhan", "Python")
student2 = Student("Omkar", "Java")
student3 = Student("Komal", ".NET")

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

Output:

Samadhan Python
Omkar Java
Komal .NET

The same constructor is reused for all three objects, but each object stores different values.

3. Constructor with Default Arguments

A constructor can also have default values for its parameters.

If the user does not pass a value, Python uses the default value.

Example

class Student:

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


student1 = Student("Samadhan")
student2 = Student("Omkar", "Java")

print(student1.name, student1.course)
print(student2.name, student2.course)

Output:

Samadhan Python
Omkar Java

For student1, the course value is not passed, so Python uses the default value Python.

For student2, the value Java is passed, so that value is used.

Understanding self

self refers to the current object.

We use self to store values inside the object.

class Student:

    def __init__(self, name):
        self.name = name


student1 = Student("Rahul")

print(student1.name)

Output:

Rahul

Here, self.name belongs to the current student object.

Constructor with a Method

We can initialize values using a constructor and then use another method to perform an operation.

class Student:

    def __init__(self, name, course):
        self.name = name
        self.course = course

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


student1 = Student("Neha", "Python")

student1.display()

Output:

Name: Neha
Course: Python

Constructor Execution Flow

Step 1: Create a class.

Step 2: Define the __init__() method.

Step 3: Create an object.

Step 4: Python automatically calls __init__().

Step 5: Initial values are assigned to the object.

Step 6: The object is ready to use.

What If We Do Not Define __init__()?

A class does not always need a custom __init__() method.

class Student:
    pass


student1 = Student()

print("Object created")

Output:

Object created

However, when we need to initialize object data, defining a constructor is useful.

Common Mistakes

  • Writing init() instead of __init__().
  • Forgetting self.
  • Forgetting self. before instance variables.
  • Passing the wrong number of arguments.
class Student:

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


student1 = Student("Rahul", 22)

Here the constructor expects two values: name and age.

Constructor Types Comparison

Type Values Passed? Example
Default / Non-Parameterized No extra values Student()
Parameterized Yes Student("Rahul", 22)
Default Arguments Optional Student("Rahul")

Complete Example

Let's combine constructor initialization with a method.

class Employee:

    def __init__(self, name, department, salary):
        self.name = name
        self.department = department
        self.salary = salary

    def display(self):
        print("Name:", self.name)
        print("Department:", self.department)
        print("Salary:", self.salary)


employee1 = Employee(
    "Rahul",
    "IT",
    60000
)

employee1.display()

Output:

Name: Rahul
Department: IT
Salary: 60000

Practice Programs

  1. Create a Student class using a default constructor.
  2. Create a Student class using a parameterized constructor.
  3. Create an Employee class with name and salary.
  4. Create a constructor with a default course value.
  5. Create three objects using the same constructor.
  6. Add a display() method to show object information.

Summary

A constructor is used to initialize an object when it is created. Python commonly uses the __init__() method for initialization. A constructor can be written without extra parameters, can accept parameters, or can use default parameter values. The self keyword is used to store data inside the current object.