My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Constructors in Python - in simple words

Constructors in Python - in simple words

Jyoti Bisht's photo
Jyoti Bisht
·Apr 25, 2021·

4 min read

Constructors in Python

Table of contents:

  1. Introduction to constructors
  2. Understanding constructors with an example
  3. Types of constructors 4 Important points to remember

Introduction to constructors

This article assumes that we are familiar with the idea of objects in Python. If not, then no worries !. You can read all about objects in Python here. As we know, objects are instances of a class. But sometimes we might need to initialize the members of the class. For example, if my class contains a data member called “age” then I want the age to be initialized with a value of 0 when an object of this class is created. How do we achieve this? With the help of something known as a constructor.

The process of initializing is known as instantiating an object. Now that we understand what we mean by instantiating, let us see what a constructor looks like and how it achieves the task of initialization.

Python has a special method written as init()”. This method is a constructor. So what does it mean anyway? It means that whenever we create an object of a class, the init() method gets called automatically and initializes our object. But with what values does it initialize it? Well, the values we specify inside the init() method are used to initialize the data members. Let us understand this by example. Consider the following python code:

class person:
    #constructor to initialize the data member "age"
    def __init__(self):
        self.age = 5

    # to see what is the value of age now
    def print_val(self):
        print(self.age)

#creating an instance i.e. creating an object of the class "person"
obj = person()
obj.print_val()

What happened here? Follow along with me :

Step 1 -> We created a person class that has 2 methods - first being our constructor init() and second being our print_val function to see what the value of age is.

Step 2 -> we created an object named obj of the person class. Now carefully understand what happens here. As soon as the object is created, i.e. the line obj = person() executes, the init() method of person class is called automatically. When called, it gets executed, and then self, age = 5 is put into action and hence the value of age is assigned as 5!. Make sure to especially focus on the parameter in init(self). What is self? It is a reference to the object created. Step 3-> we called the print_val method to print the value of age.

Great! Now we understand how the constructor works and how can it be used to initialize data members in python. Now let us see how many types of constructors can be there?

Types of constructors:

We know that init() is a python method. And methods can have arguments. Hence init() can or cannot have arguments. The init() method without arguments is known as a default constructor and when you provide it with parameters, then it is called a parameterized constructor.

What we saw in the code snippet above is called as default constructor. let us have a look at what a parameterized constructor looks like.

class person:
    #constructor to initialize the data member "age"
    def __init__(self, n, g):
        self.age = 5
        self.name = n
        self.gender = g

    def print_val(self):
        print(self.age)
        print(self.name)
        print(self.gender)

# creating an instance i.e. creating an object of the class "person"
obj = person('jyoti bisht', 'F')
obj.print_val()

That’s it!. This was our simplified introduction to constructors and how they work in python.

Some of the important points to remember :

  • Python doesn’t support multiple constructors - we can create multiple init() methods but the last one would override the earlier definitions.

  • What if we want to return something from the init() method?. Any non-None value returned from our function will raise a TypeError.

  • Can constructors follow inheritance? yes, it can!.

This was all for this blog, continue to read more !. For any doubts, feel free to reach me on LinkedIn and if you liked this blog, please consider giving me a thumbs up!.