Python Constructors – Best Ways to Implement Constructors

In this article, we will explore the concept of constructors in Python, which are essential for initializing data attributes within a class. Before diving into constructors, it’s important to understand the basics of classes and objects in Python. A class serves as a blueprint for creating objects, encapsulating data and behavior together. Objects are instances of classes, representing specific entities with unique attributes and methods.

Constructors provide a way to set up the initial state of an object when it is created, ensuring that all necessary attributes are properly initialized. By the end of this article, you’ll have a solid understanding of how to implement and utilize constructors in Python to build robust and maintainable code.

Why use Python Constructors?

Before delving into constructors in python, we first need to get the hang of one important concept. That is, in Python, you can’t use a variable before assigning it a value, no matter where you use the variable.

To demonstrate the seriousness of this issue, consider this short session at the Python Shell.

The first statement fails to execute when we define neither of the variables.

>>> x += y

Output:

NameError: name ‘x’ is not defined

The interpreter complains that ‘x’ is not defined!

Let’s now define ‘x’ and then see what the interpreter has to say.

>>> x = 10
>>> x += y

Output:

NameError: name ‘y’ is not defined

The interpreter complains again! This time it says ‘y’ is not defined.

Say no more interpreters! We’ll define ‘y’ too for you.

>>> y = 1
>>> x += y
>>> x
11
>>> y
1

Voila! It works now.

The bottom line is, no matter where you use variables in Python, you have to initialize them with a starting value.

But the question here is: how do we do this for a new object created from a class?

In object-oriented programming, “constructors” take care of this situation. In other OOP languages, a constructor is a special method that is responsible for both object instantiation (i.e. creating a new object) and attribute initialization (i.e. assigning values to the attributes for that object).

But in Python, the interpreter automatically handles the object instantiation part. So all you need a constructor for is attribute initialization.

So we now know the “why”, let’s move on to the “how”!

Coding Constructors

We said in the last section that a special method is responsible for assigning values to attributes of an object. This special method, or as we like to call in Python, this “magic method” is the __init__ method.

Let’s add __init__ to a class Student that has two attributes, name and roll number.

For now, let the __init__ method be empty with just a pass statement inside it (we’ll add some behavior just in a moment).

class Student:
    def __init__(self):
        pass
    def show(self):
        print("Name: ", self.name)
        print("Roll no.: ", self.roll)

Note that like every other method defined in a class, the __init__ method too needs “self” as its first parameter.

Now, all we need is to use __init__ to initialize our class’s attributes (name and roll). The question is: where do we get these initialization values from and how do these values get into __init__?

Passing arguments to __init__

We can pass as many arguments to __init__ as we like. All we have to do is to give our arguments names.

So let’s add arguments named n and r to initialize our attributes self.name and self.roll respectively.

class Student:
    def __init__(self, n, r):
        self.name = n
        self.roll = r
    def show(self):
        print("Name: ", self.name)
        print("Roll no.: ", self.roll)

Now that we have implemented a python constructor for our class Student, all we need to do is to pass actual values to the arguments n and r.

We do this while object instantiation, i.e., creating a new object for the class.

Let’s create an object s1 from the class Student.

s1 = Student(“Ross”, 10)

We pass two arguments, “Ross” which goes into s1.name and 10 which goes into s1.roll for the object s1. We can now call the show() method on the object s1.

>>> s1 = Student(“Ross”, 10)
>>> s1.show()
Name: Ross
Roll no.: 10
>>> s2 = Student(“Rachel”, 9)
>>> s2.show()
Name: Rachel
Roll no.: 9
>>>

We can create as many objects as we want and each object can have different values for their attributes.

We can also access the attributes of the objects using the dot operator as s1.name, which returns the value of the attribute name of object s1.

>>> s1.name
‘Ross’
>>> s2.roll
9

Types of Python Constructors

Python constructors

Constructors in Python can be of two types:

a. Parameterized Constructor in Python

Parameterized constructors are ones which have parameters(other than self) defined in the __init__ method’s parameter list. This type of constructor can take arguments from the user.

The Student class we discussed above has a parameterized constructor.

Student’s constructor takes two arguments (other than self), n and r.

b. Non-parameterized Constructor in Python

It is also known as the default constructor.

The __init__ method includes a single parameter self. No other parameters are present in __init__’s parameter list.

Consequently, this constructor takes no arguments while creating a new object.

Non-parameterized constructors assign default values to the attributes of the class.

The student class’s __init__ method can be converted to a non-parameterized constructor as follows:

class Student:
    def __init__(self):
        self.name = “Monica”
        self.roll = 15
    def show(self):
        print("Name: ", self.name)
        print("Roll no.: ", self.roll)

As you would have noticed, the __init__ method has no parameters other than self.

And the python interpreter assigns the default values “Monica” and 15 to the attributes self.name and self.roll, respectively.

We can create an object s3 as:

>>> s3 = Student()
>>> s3.show()

Output:

Name: Monica
Roll no.: 15

Let me show you a Python trick:

You can combine the concept of default and parameterized constructors in python. We know that methods are functions in disguise.

Like functions, methods can also take default parameters.

So we can modify the __init__ method of class Student to include default values for its parameters n and r.

def __init__(self, n = “Monica” , r = 15):
    self.name = n
    self.roll = r

Now we pass no argument, name and roll get the default values “Monica” and 15, respectively.

Else, the attributes will take the values of the arguments we pass.

Go ahead and test it in Python shell:

>>> s4 = Student()
>>> s5 = Student(“Joey”, 20)
>>> s4.show()
Name: Monica 
Roll no.: 15
>>> s5.show()
Name: Joey
Roll no.: 20

Wrapping Up!

This python article introduced you to Python constructors. You also learned why our program needs these constructors in python and how we can implement them.

We also came across the types of python constructors, ending with a subtle trick you can use in your program while working with constructors.

Hope you enjoyed the article as it cleared your concepts.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.