Magic Methods: An Underrated Gem of Python OOP
Most common magic methods in Python summarised in a single frame.
Magic Methods (also called dunder methods) are special methods defined inside a Python class' implementation.
On a side note, the word “Dunder” is short for Double Underscore.
They are prefixed and suffixed with double underscores, such as __len__,
__str__
, and many more.
Magic Methods offer immense flexibility to define the behavior of class objects in certain scenarios.
For instance, say we want to define a custom behavior for adding two objects of our class (obj1 + obj2
).
An obvious and straightforward to do this is by defining a method, say add_objects()
, and passing the two objects as its argument.
While the above approach will work, invoking a method explicitly for adding two objects isn't as elegant as using the +
operator:
This is where magic methods come in. In the above example, implementing the __add__
magic method will allow you to add the two objects using the +
operator instead.
Thus, magic methods allow us to make our classes more intuitive and easier to work with.
As a result, awareness about them is extremely crucial for developing elegant, and intuitive pipelines.
The visual summarizes ~20 most commonly used magic methods in Python.
Over to you: What other magic methods will you include here? Which ones do you use the most? Let me know :)
👉 Read what others are saying about this post on LinkedIn and Twitter.
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.
👉 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 and Twitter.