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.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new about Python and Data Science every day.
👉 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!
Check out Sourcery, an automated code refactoring tool for Python to make your code more elegant, concise, and pythonic.
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.