Discover more from Daily Dose of Data Science
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
__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
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 :)
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (250+ pages) with 200+ tips.
👉 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.