HOWTO · Python
How to Overload Operator in Python
This tutorial demonstrates the concept of operator overloading, its types, and code implementation in Python.
On this page
Operator overloading lets a custom Python type define what familiar operators mean for its objects. For example, + adds numbers and joins strings. It is one way types support polymorphism: the same operator expression can behave according to the operand types. See polymorphism for the broader concept.
How Python Dispatches Operators to Special Methods
Python connects operator expressions to special methods, also called dunder methods because their names begin and end with double underscores. For a binary expression such as left + right, Python uses the operands’ types to select the ordinary __add__() and reflected __radd__() methods. If the right operand’s type is a strict subclass of the left operand’s type and overrides the reflected method, Python can try that right-side method before the left operand’s ordinary method. Separately, when the left method returns the singleton NotImplemented, Python can fall back to the right operand’s reflected method when applicable. If neither side supports the operation, the expression fails with TypeError.
Return NotImplemented when an operand type is unsupported; do not raise it or return the string "NotImplemented". This lets Python continue dispatching. The same pattern applies to other binary operators through their corresponding special methods.
Implement Addition with add()
A useful addition method checks the other operand’s type, then returns a new value of the same custom type. The following example supports adding two Score objects and declines other types so Python can consider reflected dispatch.
Run this example:
class Score:
def __init__(self, value):
self.value = value
def __add__(self, other):
if not isinstance(other, Score):
return NotImplemented
return Score(self.value + other.value)
result = Score(2) + Score(3)
print(result.value)
5
The addition result is 5. For mixed-type addition, the other type can implement __radd__() to handle a Score on the right. Implement both methods only when that mixed-type operation has a clear meaning.
Implement Ordering with gt()
Define __gt__() to express the meaning of left > right for your type. A comparison should normally return the Boolean value True or False, rather than a sentence or another truthy object. This example compares objects by their numeric values.
class Measurement:
def __init__(self, value):
self.value = value
def __gt__(self, other):
if not isinstance(other, Measurement):
return NotImplemented
return self.value > other.value
print(Measurement(5) > Measurement(3))
True
The comparison result is True. Returning NotImplemented for an unsupported operand lets Python follow comparison dispatch rules instead of treating unlike values as comparable by accident.
Define Equality with eq()
Use __eq__() to define what it means for two instances to be equal. For a value object, compare the fields that determine its identity and return a Boolean. Returning "Equal" is not equivalent: that nonempty string is truthy, so it can make an equality check appear true even when it does not represent a Boolean result.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
print(Point(2, 3) == Point(2, 3))
True
The equality result is True. Choose equality fields consistently with how callers understand the object. Defining equality also affects hashing: mutable value objects should not be made hashable unless their equality-relevant state remains stable.
Operator Limits and Practical Design
Overloading changes an operator’s behavior for your type, not the operator’s shape. A unary operator such as ~value has one operand; a binary operator such as left + right has two. A special method cannot turn one form into the other.
Keep each overload intuitive for the type, return a value callers can use in the next expression, and handle unsupported operand types through NotImplemented where Python’s dispatch can continue. Use the corresponding methods for each operation rather than assigning unrelated meanings to familiar symbols. These choices make custom objects work predictably alongside built-in types.