Python Constructor- Parameterized and Non-Parameterized

1. Objective

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

2. 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
Let’s take a look at Python Slice Constructor
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()

What value?8

>>> t.val

Output – ‘8’

3. Declaring a Python Constructor

a. 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’>
Let’s learn about Python Syntax

b. 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.

c. 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

4. 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.
Let’s take a tour to Python Copy

5. 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.

a. 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 🙂

b. 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? 🙂

c. 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

Python Interview Questions

6. No Constructor Overloading in Python

a. 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

b. 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()

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__.
Have a look at Python Assert Statements

c. 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.

7. Conclusion – Python Constructor

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. Still, if you have any query, feel free to ask in the comment tab.
See also – 
Python Multiple Inheritance
For reference

1 Response

  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

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.