What is the purpose of the python class initializer?

Posted by Marta on January 13, 2021 Viewed 46 times

This tutorial will help you to understand what is a python class initializer and its purpose in python. Including examples with the source code.

Card image cap

Hey there! Have you seen python class initializers everywhere? However, what is their purpose? This tutorial will help you to understand what is a python class initializer and its purpose in Python.

As you probably know, a class is used in object-oriented programming to represent a problem’s entities. Using a class, you can define any real-world concept, such as an animal, a person, a machine, a product, anything.

Classes and objects in Python

You could see a class as a custom data structure that contains both data and code. When you create a class, you define the type of data your class will hold and the class’s operations. Once you create your class, you can create an instance of this class with real data, known as objects. In other words, an object is to its class as four is to the int type.

For instance, I could create a Furniture class and then add two data pieces to this class, the type(chess, sofa, table, etc.) and material(wood, plastic, etc.).

Python class initializer

Once you define your class, the next step is creating a variable of this class containing real data. That is what the initializer, or constructor, does. It determines the class attributes(data) and how values will be assigned to these attributes. In Python, that is the purpose of the __init__; it determines how to create the object. Let’s use the Furniture class mentioned earlier.

class Furniture:
    def __init__(self, parameter_type, parameter_material):
        self.type = parameter_type
        self.material = parameter_material

    def show_details(self):
        print('Furniture: '+ self.type + ' made of '+self.material)


bedroom_furniture = Furniture('bed','wood')
bedroom_furniture.show_details()

livingroom_furniture = Furniture('table','wood')
livingroom_furniture.show_details()

Output:

Furniture: bed made of wood
Furniture: table made of wood

In lines 10 and 11, the code creates an instance of a Furniture class, each with different values. Each line will automatically call the __init__ method, also known as the initializer or constructor method.

In this case, the __init__ method indicates that you need to pass two parameters to create a Furniture class. The first parameter gets assigned to the type attribute and the second parameter to the material attribute.

At this point, any other class method can use this value to perform any other operation. For instance, in the example the class method show_details() will use the type and material attributes.

Another example

Let’s see another example. In this instance, I will create a class Square, containing one piece of information, the side length in centimeters. Also, add a class method that will return the square area. See below how to achieve this:

class Square:
    def __init__(self, p_side_in_cms):
        self.side_in_cms = p_side_in_cms

    def calculate_area(self):
        return self.side_in_cms * self.side_in_cms

# Square object #1
square1 = Square(10)
print("The area of the first square is: "+str(square1.calculate_area())+ "cm2")

# Square object #2
square2 = Square(6)
print("The area of the first square is: "+str(square2.calculate_area())+ "cm2")

Output:

The area of the first square is: 100cm2
The area of the first square is: 36cm2

Is __init__ necessary in Python?

No, the __init__ method is not always necessary, and it is not mandatory. You can create a class and define no constructor; however, if your class has instance fields, I would advise you to create a constructor. Here is an example of a class with no constructor defined:

class Example:
    def method(self, value):
        return value*2


value1 = Example().method(4)
print(value1)

Output:

8

How can this go wrong?

We have seen how to define a class and its constructor correctly. Now I will show a code snippet that raises an error, so you know what not to do. The following code will encounter an AttributeError.  Have a look at the code and try to think what is causing the problem.

class Person:
    def __init__(self, name, age):
        self.name = name

    def double_age(self):
        return self.age * 2

# Person object #1
person1 = Person('Peter',18)
print(person1.name + " double age is "+ str(person1.double_age()))

Output:

File line 10, in <module>
    print(person1.name + " double age is "+ str(person1.double_age()))
  File line 6, in double_age
    return self.age * 2
AttributeError: 'Person' object has no attribute 'age'

Did you find it? That’s right. The origin of the issue is line 6. The code is referring to the class attribute self.age; however, this attribute was not initialized in the constructor. How can you fix it? It would be best to initialize the age attribute to add the following line right after line 3.

        self.age = age

Once you added the above line, the error will disappear.

Conclusion

In this tutorial, you learn that the purpose of the python class initializer is defining the class attributes and assigning values to these attributes. In other words, it determines how to build an object of a given class.

Thanks for reading and supporting this blog! Happy Coding! 🙂

More Interesting Articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java