Python: __init__ is NOT a constructor: a deep dive in Python object creation | by Mike Huls | Nov, 2023

Editor
2 Min Read


Tinkering with Python’s constructor to create fast, memory-efficient classes

How Python builds objects (image by ChatGPT)

Did you know that the __init__ method is not a constructor? But if __init__ doesn’t create the object, then what does? How do objects get created in Python? Does Python even have a constructor?

The goal of this article is to better understand how Python creates objects so that we can do manipulate if for useful applications.

First we’ll take a deepdive in how Python creates objects. Next we’ll apply this knowledge and discuss some interesting use cases with some practical examples. Let’s code!

In this part we’ll figure out what Python does under the hood when you create an object. In the next part we’ll take this new knowledge and apply in in part 2.

How to create an object in Python?

This should be pretty simple; you just create an instance of a class. Alternatively you could create a new built-in type like a str or an int. In the code below an instance is created of a basic class. It just contains an __init__ function and a say_hello method:

class SimpleObject:
greet_name:str

def __init__(self, name:str):
self.greet_name = name

def say_hello(self) -> None:
print(f"Hello self.greet_name!")

my_instance = SimpleObject(name="bob")
my_instance.say_hello()

Notice the __init__ method. It receives a name parameter and stores its value on the greet_name attribute of the SimpleObject instance. This allows our instance to keep state.

Now the question rises: in order to save the state, we need to have something to save the state on. Where does __init__ get the object from?

So, is __init__ a constructor?

The answer: technically no. Constructors actually create the new object; the __init__ method is only responsible for setting the state of the object. It just receives values through it’s parameters and assigns them to the class attributes like greet_name.

Share this Article
Please enter CoinGecko Free Api Key to get this plugin works.