Constructor in Python

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

A constructor is a special method in a class used to create and initialize an object of a class. There are different types of constructors. Constructor is invoked automatically when an object of a class is created.

What is a Constructor?

A constructor is a unique function that gets called automatically when an object is created of a class. The main purpose of a constructor is to initialize or assign values to the data members of that class. It cannot return any value other than none.

Let's see how to use the constructor.

Syntax of Python Constructor

def __init__(self):
	# initializations

init is one of the reserved functions in Python. In Object Oriented Programming, it is known as a constructor.

Rules of Python Constructor

  • It starts with the def keyword, like all other functions in Python.
  • It is followed by the word init, which is prefixed and suffixed with double underscores with a pair of brackets, i.e., __init__().
  • It takes an argument called self, assigning values to the variables.

Self is a reference to the current instance of the class. It is created and passed automatically/implicitly to the __init__() when the constructor is called.

Types of Constructors in Python

  1. Parameterized Constructor
  2. Non-Parameterized Constructor
  3. Default Constructor

1. Parameterized Constructor in Python

When the constructor accepts arguments along with self, it is known as parameterized constructor.

These arguments can be used inside the class to assign the values to the data members. Let's see an example:

Code:

class Family:  
    # Constructor - parameterized  
    members=5
    def __init__(self, count):  
        print("This is parametrized constructor")  
        self.members = count
    def show(self):  
        print("No. of members is", self.members)  
        
object = Family(10)  
object.show()   

Output:

This is parameterized constructor
No. of members is 10

Explanation

  • An object of the class Family is created. It has a variable known as members.
  • When the object is created, a parameter (here it is 10) is passed as arguments.
  • This parameter (10 as in the above example) is taken up by the constructor as the object is created.
  • The number 10 is assigned to the variable count, which is further assigned to self.members.
  • The self.members can be used within the class to print the data.

2. Non-Parameterized Constructor in Python

When the constructor doesn't accept any arguments from the object and has only one argument, self, in the constructor, it is known as a non-parameterized constructor.

This can be used to re-assign a value inside the constructor. Let's see an example:

Code:

class Fruits:
    favourite = "Apple"

    # non-parameterized constructor
    def __init__(self):
        self.favourite = "Orange"

    # a method
    def show(self):
        print(self.favourite)


# creating an object of the class
obj = Fruits()

# calling the instance method using the object obj
obj.show()

Output:

Orange

Explanation:

In the above example, we initialize our favorite fruit as Apple inside the class. But we want to change it as soon as the object gets created.

This can be done by re-assigning the value to the constructor. This type of constructor doesn't take any other argument other than self. It can be used to print and check whether our value got changed.

3. Default Constructor in Python

When you do not write the constructor in the class created, Python itself creates a constructor during the compilation of the program.

It generates an empty constructor that has no code in it. Let's see an example:

Example

class Assignments:
    check= "not done"
    # a method
    def is_done(self):
        print(self.check)

# creating an object of the class
obj = Assignments()

# calling the instance method using the object obj
obj.is_done()

Output

not done

Explanation

In the above example, we check whether our assignment is done.

We create an object of a class where we do not write the constructor.

Python generates a constructor when we do not provide any to initialize the instance variables. It does nothing.

Conclusion

  • The constructor is a method that is called when an object is created of a class.
  • The creation of the constructor depends on the programmer, or else Python will automatically generate the default constructor.
  • It can be used in three types - Parameterized Constructor, Non-Parameterized Constructor, Default Constructor.
Challenge Time!
quiz
quiz
Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.
Free Courses by top Scaler instructors
rcbGet a Free personalized Career Roadmap from