Topics

The concept of Constructor

Welcome to a tutorial on Constructors to create a Class Object in Python. Here you will learn how to create a class, its instance and how to access class members, be it variables or functions.

As will proceed, we will broaden our understanding of classes. As we already know that the class keyword is typically used to initiate the definition of a class and then followed by the class. That is to say that, after finishing the first line with a colon we move to the next line and start defining variables or methods after providing proper indentation.

 

What is a Constructor?

There are two ways to declare or define a variable of a class, just as discussed in our previous tutorial.

The first thing is to define the variable inside the class and probably initialize it with a value. Check out the example below:

class Example:
	myVariable = "some value";

 

Then, the second thing or way is to declare it inside any function of the class by making use of the self keyword.

In addition, we can also assign values to the variables while declaring them, however, in most scenarios, the values of these variables might vary for different objects of the same objects of the same class. Therefore, we have to assign values to the variables after the creation of the object. Check out the example below, as this can be done in two ways by calling each variable from the object by making use of the dot . symbol.

>>> myObject.myVariable = "some other value";

or the user can be asked for input.

>>> myObject.myVariable = input();

 

Aside from this, values of our variables can be assigned/modified inside the class functions by using the self keyword.

class Example:
	def anotherFunction(self, parameter1):
		self.myVariable = parameter1;
		# or by calling for a user input
		self.myVariable = input();

 

Now, if we have such a function defined in our class, therefore, the object's variables can be initialized or re-initialized by calling the anotherFunction() method and passing the desired value as a parameter to this method or function.

>>> myObject = Example()
>>> myObject.anotherFunction("Amazing Python")
>>> print (myObject.myVariable)

Output:

Amazing Python

As shown above, this was a usual user-defined function inside Example class that utilized parameters to initialize the variable. The concept is quite simple, although, there exists something better, which uses the same principle and is a defined standard as well, and is known as a Constructor.

In Python, a Constructor is a special type of function that is called automatically at any time an object of that class is created. Check out the example below.

>>> myObject = Example();

If we Example() in the code of the example above, we are informing python that myObject is an object of class Example. At this point, the constructor of that class is called.

The question here is, what will the constructor do? The constructors are generally used to initialize the variables of the class for the class of an object (or instance), thus, they can perform other tasks, such as checking if there are enough resources and if the value used to initialize any variable is valid or not, and so on.

 

Defining Constructor method in a class

The creation part of object creation is divided into two parts:

  • Object Creation
  • Object Initialization

 

Object Creation

The static class method is used to control Object creation with the name __new__. Thus, if you call Example(), to create an object of the class Example, as such the __new__ method of this class is called. The Python language defines this function for every class by default. Check out the example below.

class Example:
    def __new__(self):
        return 'studytonight';

# creating object of the class Example
mutantObj = Example()

# but this will return that our object 
# is of type str
print (type(mutantObj))

From the above example, the __new__ function was used to change the type of object returned.

Check out the example below to learn more about how the default __new__ function works.

class Example:
	myVariable = "some value";

simpleObj = Example()
print (type(simpleObj))

 

Object Initialisation

In Python, object initialization is controlled by an instance method with the name __init__, which is generally called a Constructor as well. However, the __new__ and __init__ together form a constructor.

If the object has been created, we can make sure that each variable in the object is initialized correctly by defining an __init__ method in our class, meaning init-iate.

Therefore, it is not a big deal what the class name is, because if you decide to write a constructor (I.e. to initialize your object) for the class, you have to use the __init__() method. Thus, inside this function, you are at liberty to declare a class variable (by using self) or probably initialize them. Check out the example below:

class Example:
	def __init__(self, value1, value2):
	    self.myVariable1 = value1;
		self.myVariable2 = value2;
		print ("All variable initialized")

From the example, we define the __init__ method in a class while creating an object, when you call Example(). One can give all the necessary parameters required for the object's variables because when the Example() is called; behind the scenes python calls the __init__ function automatically for the created object.

Check out the example below:

>>> myObj = Example("first variable", "second variable")

This function can be used for initialization in different ways. We have mentioned some of the parameters, and another way could be requesting the user for input inside the constructor.

def __init__(self):
	self.myVariable1 = input();
	self.myVariable2 = input();

The summary of all that we have learned is shown in the diagram below: