Member-only story
6 Best Practices for Defining the Initialization Method In Python
Write readable and maintainable Python code
The essential cornerstone of Python as an object-oriented programming language is the definition of related classes to manage and process the data in your programs. When we create our classes, the first method that we define is the initialization method: __init__
. Applying the best practices to this method will ensure that it’s easy for readers to understand the class’s instance objects. In this article, I’d like to review these best practices for defining the __init__
method.
1. Place It at The Top
It sounds obvious to most of us, but I have seen people “hide” it deep in the body of the class, together with other attributes. It’s important to place it at the top of the class, before any other methods. This is where readers should look for the __init__
method.
If you have class attributes, you should place the __init__
method after these class attributes. You must do it consistently across all the classes that you define for your project so that readers won’t be confused.
2. Name the First Parameter As Self
First of all, you should understand what the first parameter means. The first parameter refers to the instance object that invokes the __init__
method. You may have heard the term instantiation, but the __init__
method itself isn’t equivalent to instantiation. As the name indicates, __init__
means initialization, which refers to the process of setting the initial state of the newly created instance object.
As a convention, it’s important for you to name the first parameter as self, although it’s not required to do so. As a side note, self
isn’t a keyword in Python, unlike many other languages which may use this
, self
, or it
which serve as reserved keywords to refer to the current calling instance object.
3. Set All Instance Attributes
Python doesn’t restrict where you define instance attributes within your class. However, it doesn’t mean that you can spread the instance attributes everywhere in your class. Consider the following example: