Most Python Programmers Don't Know This About Python OOP

Demystifying the __init__() method.

Most python programmers misunderstand the __𝐢𝐧𝐢𝐭__() method. They think that it creates a new object. But that is not true.

When we create an object, it is not the __𝐢𝐧𝐢𝐭__() method that allocates memory to it. As the name suggests, __𝐢𝐧𝐢𝐭__() only assigns value to an object's attributes.

Instead, Python invokes the __𝐧𝐞𝐰__() method first to create a new object and allocate memory to it. But how is that useful, you may wonder? There are many reasons.

For instance, by implementing the __𝐧𝐞𝐰__() method, you can apply data checks. This ensures that your program allocates memory only when certain conditions are met.

Other common use cases involve defining singleton classes (classes with only one object), creating subclasses of immutable classes such as tuples, etc.

👉 See what others are saying about this post on LinkedIn: Post Link.

👉 If you love reading this newsletter, feel free to share it with friends!

Find the code for my tips here: GitHub.

I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn.

Reply

or to participate.