How to override the operator in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, you do not override operators directly. You implement special methods, often called dunder methods, and Python maps operators to those methods. This is how custom classes can support +, ==, [], len(), and many other language features.
How Operator Overloading Works
Python defines a special method for each supported operation. A few common examples are:
- '
__add__fora + b' - '
__eq__fora == b' - '
__getitem__fora[index]' - '
__len__forlen(a)' - '
__mul__and__rmul__for multiplication in both operand orders'
You should overload only operators that make semantic sense for the type. Good operator overloading makes code clearer. Bad operator overloading makes code mysterious.
Arithmetic Example With +
Here is a small vector class that supports addition.
The important detail is return NotImplemented for unsupported types. That allows Python to try the reflected method on the other operand or eventually raise a proper TypeError.
Support Both Operand Orders
If your type should work on the right side of an operator, implement the reflected version too. Multiplication is a common example.
Without __rmul__, 3 * v would fail even though v * 3 works.
Overload [] With __getitem__
The article tag suggests the indexing operator, so it is worth calling out separately. To support obj[index], implement __getitem__.
This makes sense because Pair has a clear positional interpretation. If your object is not naturally indexable, do not force __getitem__ onto it.
Equality and Hashing Need Consistency
If you overload comparison, think about hashing and mutability. Equal objects should behave consistently in sets and dictionaries.
This example also shows that operator overloading should reflect domain rules. Adding different currencies blindly would be misleading.
In-Place Operators
Operators such as += can use in-place methods like __iadd__. Choose carefully whether the object should mutate or return a new value.
For immutable value objects, returning new instances is often the better design. For mutable counters or buffers, in-place behavior can be natural.
Common Pitfalls
A common mistake is returning None instead of NotImplemented for unsupported operands. Another is overloading operators that do not match user expectations, which makes an API clever but hard to trust.
It is also easy to forget reflected methods, so mixed operand order fails unexpectedly. Finally, if you overload equality on mutable objects, be careful about using them as dictionary keys.
Summary
- Python overloads operators through special dunder methods.
- Implement only the operators that make sense for your type.
- Return
NotImplementedfor unsupported operand types. - Use reflected methods such as
__rmul__when operand order should not matter. - Keep equality, hashing, and mutability behavior consistent.
Related reading
- How to pass a parameter to a fixture function in Pytest?
- How to pass along username and password to cassandra in python
- How to pass another entire column as argument to pandas fillna
- How to pass arguments to a Button command in Tkinter?
- How to pass body into aiohttp get request?
- How to pass pandas dataframe to airflow tasks
- How to pass two estimator objects to sklearn's GridSearchCV so that they have the same parameters in each step?
- how to patch configmap field using python client library
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.