Course contentsShow
← Python
Lesson 449 of 1,0607. Object-Oriented ProgrammingFree lesson

Supporting Reflected Arithmetic Operations

Define reflected methods like __radd__ to ensure your objects behave correctly when they appear on the right side of an operator.

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:

  1. It checks if the integer 5 has an __add__ method that supports Box. It doesn't.
  2. It then checks if b has an __radd__ method.
  3. Because b has __radd__, Python invokes b.__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.