I prepared the following visual, which lists the 20 most common magic methods used in Python OOP:
In my experience, these are possibly the only 20 magic methods you would ever need in most Python projects utilizing OOP.
Syntactically, they are prefixed and suffixed with double underscores, such as __len__,
__str__
, and many more. That is why they are also called “Dunder methods” — short for Double UNDERscore.
Here’s a brief description of each of them.
__new__
:This method is invoked before
__init__
to allocate memory to an object.In most cases, we wouldn’t need it.
Yet, at times, I have used this to define checks and allocate memory only when certain conditions are met.
Another common usage is to define singleton classes — classes with only one object.
__init__
:Most common in this list.
This is invoked after memory allocation to assign value to an object’s attributes.
__str__
:Executing
print(obj)
outputs the memory address of the object, which is not interpretable.Defining this method lets us print the object in a readable format.
__int__
: Invoked when we execute →int(obj)
.__len__
: Invoked when we execute →len(obj)
.__call__
:Invoked when a class object is called as a function →
obj()
.
__getitem__
: Invoked when an object is indexed →obj[key]
.__setitem__
: Invoked when an object is indexed and a value is set →obj[key]=value
.__delitem__
: Invoked when an object’s index is deleted →del obj[key]
.__contains__
: Invoked when thein
operator is used →item in obj
.__bool__
: Invoked when an object is used in a boolean context →if obj or bool(obj)
.__iter__
: Invoked when we iterate over an object →for x in obj
.__eq__
: Invoked when==
operator is used to compare two objects →obj1 == obj2
.__ne__
: Invoked when!=
operator is used to compare two objects →obj1 != obj2
.__gt__
:Invoked when
>
operator is used to compare two objects →obj1 > obj2
.Other than
__gt__
, we also have:__lt__
: less than.__le__
: less than or equal to.__ge__
: greater than or equal to.
__add__
: Invoked when two objects are added →obj1 + obj2
.__mul__
: Invoked when two objects are multiplied →obj1 * obj2
.__abs__
: Invoked when we compute the absolute value of an object:abs(obj)
.__neg__
: Invoked when the unary operator-
(minus) is used on an object →-obj
.__invert__
: Invoked when~
(tilde) operator is used to invert an object →~obj
.
That’s it.
Now you know the most common Magic methods in Python and how they are used.
We went into much more detail and covered many advanced concepts and programming details of Python OOP here: Object-Oriented Programming with Python for Data Scientists.
Also, if you want to get really good at Python OOP, learn about Python Descriptors.
I find them to be massively helpful in reducing work and code redundancy while also making the entire implementation much more elegant.
We covered it in this newsletter here: Define Elegant and Concise Python Classes with Descriptors.
👉 Over to you: Did I miss any common magic methods? If yes, which one(s)?
1 Referral: Unlock 450+ practice questions on NumPy, Pandas, and SQL.
2 Referrals: Get access to advanced Python OOP deep dive.
3 Referrals: Get access to the PySpark deep dive for big-data mastery.
Get your unique referral link:
Are you overwhelmed with the amount of information in ML/DS?
Every week, I publish no-fluff deep dives on topics that truly matter to your skills for ML/DS roles.
For instance:
A Beginner-friendly Introduction to Kolmogorov Arnold Networks (KANs).
5 Must-Know Ways to Test ML Models in Production (Implementation Included).
Understanding LoRA-derived Techniques for Optimal LLM Fine-tuning
8 Fatal (Yet Non-obvious) Pitfalls and Cautionary Measures in Data Science
Implementing Parallelized CUDA Programs From Scratch Using CUDA Programming
You Are Probably Building Inconsistent Classification Models Without Even Realizing.
And many many more.
Join below to unlock all full articles:
SPONSOR US
Get your product in front of 79,000 data scientists and other tech professionals.
Our newsletter puts your products and services directly in front of an audience that matters — thousands of leaders, senior data scientists, machine learning engineers, data analysts, etc., who have influence over significant tech decisions and big purchases.
To ensure your product reaches this influential audience, reserve your space here or reply to this email to ensure your product reaches this influential audience.
thanks