In this lesson, you will learn how to make your custom objects work smoothly with arithmetic operators even when they appear on the right side of an expression.
The Problem: Why __add__ Isn't Always Enough
When you define __add__ in your class, Python knows how to handle an expression like my_object + 5. However, if you try 5 + my_object, Python looks at the integer 5 first. Since the integer class doesn't know how to add itself to your custom object, the operation will fail with a TypeError.
To fix this, Python provides reflected (or "right-side") arithmetic methods. If the left-hand object doesn't know how to handle the operation, Python calls the corresponding reflected method on the right-hand object.
Implementing Reflected Methods
For every standard operator method like __add__, there is a corresponding reflected version prefixed with an r, such as __radd__.
Consider this Box class:
class Box:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other
def __radd__(self, other):
# We can simply point this back to __add__
# because addition is commutative
return self.__add__(other)
b = Box(10)
print(b + 5) # Calls __add__: 15
print(5 + b) # Calls __radd__: 15
How It Works
When you execute 5 + b, Python performs these steps:
- It checks if the integer
5has an__add__method that supportsBox. It doesn't. - It then checks if
bhas an__radd__method. - Because
bhas__radd__, Python invokesb.__radd__(5), which executes our custom logic.
By implementing these reflected methods, you ensure your objects behave like native Python types, allowing them to participate in mathematical expressions regardless of their position in the equation. This makes your classes much more robust and intuitive for other programmers to use.
Key Takeaway: Define reflected methods like __radd__, __rsub__, or __rmul__ to handle cases where your custom object appears on the right side of an arithmetic operator.