New Tutorials:   JAVASCRIPT    SASS/SCSS    PL/SQL  
See the Tutorial List

Python Constructors to create a Class Object

In the last tutorial, we learned how to create a class, its instance and how to access class members(variables and functions). In this tutorial, we will try to improve our understanding about classes by learning more about them. So far, it is known that class keyword is used to initiate the definition of a class, followed by the name of the class. After finishing the first line with colon we move to next line and starts defining variables or methods after providing proper indentation.

What is a Constructor?

As seen in the last tutorial, we know that there are two ways to declare/define a variable of a class.

First, by simply defining it inside the class and maybe even initialize it with some value, then and there, pretty much like:

class Example:
	myVariable = "some value";

Second way is to declare them inside any function of the class, using the self keyword.

Also, it is possible to assign values to the variables while declaring them but sometimes it may happen that the values of these variables may vary for different objects of the same class. In such cases, you'll have to go for assigning values to the variables after the object creation.

Again, this can be done in two ways. First, by calling each variable direct from the object, using the dot . symbol, like:

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

or we can also ask user for an input:

>>> myObject.myVariable = input();

Besides this we can also assign/modify values of our variables inside class functions using the self keyword.

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

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

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

Amazing Spiderman

As it can be seen, this was a usual user-defined function inside Example class which is utilising parameters to initialize the variable. The concept is fairly simple here. Although, there exists something better, which uses pretty much the same principle and is a defined standard. It's known as a Constructor.

Constructor is a special type of function that is called automatically whenever an object of that class is created. For example,

>>> myObject = Example();

By writing Example() in the code above, we are informing python that myObject is an object of class Example. And that is exactly when the constructor of that class is called.

But what will it do? Well, generally, the constructors are used to initialize the variables of the class for an object(instance), although it can perform some other tasks as well, like checking if there are enough resources, if the value used to initialize any variable is valid or not, etc.

Defining Constructor method in a class

In python, the object creation part is divided into two parts:

  1. Object Creation
  2. Object Initialisation

Object Creation

Object creation is controlled by a static class method with the name __new__. Hence when you call Example(), to create an object of the class Example, then the __new__ method of this class is called. Python defines this function for every class by default, although you can always do that explicitly too, to play around with object creation.

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))

In the example above, we have used the __new__ function to change the tyoe of object returned, just to show you what we can do using this function.

To see how the default __new__ function works, run the code below, and you will see that this time the object created is of the type Example

class Example:
	myVariable = "some value";

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

Object Initialisation

Object initialisation is controlled by an instance method with the name __init__ and which is also generally called as a Constructor. Although, both __new__ and __init__ together forms a constructor.

Once the object is created, you can make sure that every variable in the object is correctly initialised by defining an __init__ method in your class, which pretty much means init-iate.

Thus, it doesn't matter what the class name is, if you want to write a constructor(to initialise your object) for that class, it has to be the __init__() method. Within this function, you're free to declare a class variable(using self) or initialize them. Here is a quick example for our Example class with __init__ method:

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

Once you define the __init__ method in a class, then while creating an object, when you call Example(), you can provide all the necessary parameters required for the object's variables, because when we call Example(), behind the scene python calls the __init__ function for the created object automatically.

This is how the code will look:

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

You can use this function in lots of ways for initialization. One is already mentioned above using a parameter, another way could be asking user for input inside the constructor.

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

Below we have a diagram which summarises it all.

Concept of constructor in python