Posted by Marta on January 13, 2021 Viewed 1376 times
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.
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.).
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()
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
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")
The area of the first square is: 100cm2 The area of the first square is: 36cm2
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)
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()))
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.
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! 🙂
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
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