SIMPLE DIFFERENCE BETWEEN USING A CONSTRUCTOR AND NOT USING A CONSTRUCTOR IN PYTHON 3

4 April 2021, Abdulhakim Altunkaya

In this article we will try to find the difference between using a constructor and not using a constructor in python classes. By doing this, we would be able to understand better why to use constructors.

I am using python editor IDLE 3.9

OPTION 1 (WITHOUT CONSTRUCTOR 1):

This option neither uses a constructor not a special method to access variable values. Variable values are our car information like number of wheels and doors. Variables we want to display are standing independently inside the class. In other words, variable names and variable values are standing independently inside the class


this is a article image

As you can see, we access our variables without using a method. This way of class creation is easier but not scalable, in other words, you cannot use it for lets say 100 cars. Because you will have to create 200 variables (100 for wheels, 100 for doors) inside the class and another 100 function calls to display their values. As you can judge, this way would be time-consuming and not nice looking and open to making mistakes.

By the way, the result for above code block is:

4
wroommmm

OPTION 2 (WITHOUT CONSTRUCTOR 2):

This option will not use a constructor but a method to access variable values. Variable values we want to display are not standing independently. Their name are in method and their values are in function call.


this is a article image

As you can see, we access our variables by using a method. This way is scalable. For 100 cars, we don’t have create 200 variables. We just give their values in our function calls.

Result is:
vroommmm2
4

OPTION 3 (WITH CONSTRUCTOR):

This option will use a constructor to access variable values. Variable values we want to display are not standing independently. Their name are in method and their values are in Class call.


this is a article image

As you can see, we access our variables by using a constructor. This way is scalable. For 100 cars, we don’t have create 200 variables. We just give their values in our Class calls.


Result is:
vrommmm3
4

So, what is the difference between Option 2 and Option 3? Using a method or a using constructor? Constructors are also methods but they are special, they behave like class parameters. So, instead of calling function, you can call Class and it would give the same result. By doing this, we don’t have to write extra lines of code to call function.