Python Constructor- Parameterized and Non-Parameterized

Python course with 57 real-time projects - Learn Python

In our last Python tutorial, we discussed Python Identifiers. Today, we will learn about __init__(self), the Python Constructor.

Moreover, we will take a look at what we can do for it, and will learn about parameterized and non-parameterized Python Constructors.

Also, we will learn about object creation and initialization and will investigate if it is possible to overload constructors. 

So, let’s start the Python Constructor tutorial.

Python Constructor- Parameterized and Non-Parameterized

Python Constructor- Parameterized and Non-Parameterized

What is a Constructor in Python?

Python Constructor in object-oriented programming with Python is a special kind of method/function we use to initialize instance members of that class.

We can also use it to ensure we have enough resources. Whenever we create an object of that class, the constructor definition is the first to execute.

The way to initialize the value of a class attribute without a constructor:

>>> class three:
       val=7
>>> three.val

Output

7

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

We can also do this inside class functions:

>>> class three:
       def func(self,val):
              self.val=val
>>> t=three()
>>> t.func(8)
>>> t.val

Output

8
>>> t.func(6) #Also lets us re-initialize attributes
>>> t.val

Output

6

Or we can ask the user for input.

>>> class three:
       def __init__(self):
               self.val=input("What value?")
>>> t=three()

Output

What value?8
>>> t.val

Output

‘8’

Declaring a Python Constructor

1. Object Creation

__new__ is a static class method that lets us control object creation. Whenever we make a call to the class constructor, it makes a call to __new__.

While this is a default function for every class, we can definitely play around with it.

>>> class demo:
       def __new__(self):
              return 'dataflair'
>>> d=demo()
>>> type(d)

Output

<class ‘str’>

2. Object Initialization (and self-parameter)

A constructor is essentially a class function with its name surrounded by double underscores (__). We always call it __init__().

In C++ or Java, a constructor has the same name as its class, but things aren’t the same with Python. Constructors let us initialize an object.

Let’s take an example.

>>> class citrus:
       def __init__(self):
               self.detoxifying=True
def show(self):
               print("I detoxify") if self.detoxifying==True else print("I do not detoxify")
>>> kumquat=citrus()
>>> kumquat.show()

Output 

I detoxify

Now statement by statement, let’s see what’s happening.

  • __init__() is the constructor here.
  • It takes the self-keyword to tell the interpreter to work with attributes of this object. It should be the first parameter.
  • It takes no parameters.
  • When setting detoxifying to true, we use the self-keyword.
  • We have another method show(), we pass self to this too.
  • Then, we create an object as kumquat=citrus().
  • Finally, we make a call to kumquat.show().

Together, both __new__ and __init__ form a constructor.

3. New Attributes

We can also create a new attribute exclusively for this object and read it when defining values.

There is not much you can do once you have already defined the object.

>>> kumquat.color='orange'
>>> print("I am ",kumquat.color)

Output 

I am  orange

Not Declaring a Python Constructor

So what happens when we do not explicitly provide a constructor to a class? Can Python handle it?

Why don’t we try that out?

>>> class color:
        def show(self):
               print("You can see me")
>>> orange=color()
>>> orange.show()

Output

You can see me

Here, we did not define a constructor, but Python instantiated that object anyway! This must mean it provides a default constructor that shows up when we do not provide any.

Types of Python Constructors

We observe three types of Python Constructors, two of which are in our hands. Let’s begin with the one that isn’t.

1. Default Constructor in Python

A constructor that Python lends us when we forget to include one. This one does absolutely nothing but instantiates the object; it is an empty constructor- without a body.

>>> class demo:
def show(self):
print("Thank you for instantiating me :)")
>>> d=demo()
>>> d.show()

Output

Thank you for instantiating me 🙂

2. Non- Parameterized Constructor in Python

When we want a constructor to do something but none of that is to manipulate values, we can use a non-parameterized constructor.

Let’s try the previous example with this!

>>> class demo:
       def __init__(self):
               print("Thank you for instantiating me :)")
>>> d=demo()

Output

Thank you for instantiating me 🙂

We can also use this constructor to set values we’ve decided. Watch how.

>>> class demo:
       def __init__(self):
               self.color='red'
               self.drink='tea'
       def hello(self):
               print(f"Thank you for instantiating me, I'm all {self.color}. Would you like some {self.drink}? :)")
>>> d=demo()
>>> d.hello()

Output

Thank you for instantiating me, I’m all red. Would you like some tea? 🙂

3. Parameterized Constructor in Python

This lets us set custom values for instance variables. We can have any number of these.

>>> class demo:
       def __init__(self,age,country):
               self.age=age
               self.place=country
       def hello(self):
               print(f"Hello, I am a {self.age}yo from {self.place}")
>>> d=demo(22,'Romania')
>>> d.hello()

Output

Hello, I am a 22yo from Romania

No Constructor Overloading in Python

1. More than One Python Constructor

If you give it more than one constructor, that does not lead to constructor overloading in Python.

>>> class one:
       def __init__(self):
               print("First constructor")
       def __init__(self):
               print("Second constructor")
>>> o=one()

Output

Second constructor

2. Two Different Kinds of Constructors in Python

Not even if you try two different kinds of constructors:

>>> class one:
        def __init__(self):
                print("First constructor")
        def __init__(self,val):
                self.val=val
                print("Second constructor",val)
>>> o=one()

Output

Traceback (most recent call last):
File “<pyshell#58>”, line 1, in <module>
o=one()
TypeError: __init__() missing 1 required positional argument: ‘val’

What this means is Python rebinds the name __init__ to the new method. This means the first declaration of this method is inaccessible now.

Internally, __new__ is the constructor that returns a valid and unpopulated object on which to call __init__.

3. Using Default Arguments

Even the following piece of code is simply the use of default arguments, not constructor overloading:

>>> class one:
       def __init__(self,a=1,b=2):
                print(a+b)
>>> o=one(2)

Output

4
>>> o1=one(2,3)

Output

5
>>> o2=one()

Output

3

So, this was all in Python Constructor tutorial. Hope you like our explanation.

Python Interview Questions on Constructor

  1. What is Constructor in Python? Explain with example.
  2. What is the use of Constructor in Python?
  3. How many Constructors are there in Python?
  4. Can we have 2 Constructors in Python?
  5. Can Constructor in Python be private?

Conclusion

Who knew there was so much to know about constructors in Python?

We learned about parameterized and non-parameterized Python Constructors, the default Python Constructor, the self-keyword, object creation, and object initialization.

Also, we saw that there is no such thing as constructor overloading in Python. 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

6 Responses

  1. Vikas Pal says:

    why the constructor overloading is not possible in python and I don’t understand the two different type of constructor in python when they are working together ..please explain the the below error in two kind of constructor what would be very helpful to grab the concept. Thank You

    • DataFlair says:

      Python doesn’t support multiple constructors, if you define two different constructors in the same class then the first declaration will be inaccessible. This means that if your latest defined constructor is parameterized then you can create objects using only that constructor if you try using any other constructor then it will throw error.

  2. Anand Singh says:

    I came across your tutorial a few days ago and I loved your tutorial extremely very much on Python, the information present here is detailed covering almost all topics which I have also gathered while working for 3 yrs in industry ….

    I would like to understand how to use __new__ to control object creation. Can you show and explain by example since I feel its missing?

    • DataFlair says:

      Hey, sure.
      Consider this code snippet:
      class demo:
      def __new__(self):
      return ‘dataflair’
      d=demo()

      Here the __new__ function returns a string object so the type of d is also a string. You can return any type of object using __new__ function.

  3. Yash vevek katkamwar says:

    Can we overload an constructor in python?justify u r opinion

    • DataFlair says:

      No, we cannot overload a constructor in python but if you define two or more constructor in same class, it will not give error, instead it will consider the latest defined constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *