Friday, June 5, 2026

What is the difference between __mul__ and __rmul__?

All Questions From This Chapter    « Previously    Next »

In Python, __mul__ and __rmul__ are both used for the * operator, but they are called in different situations.

__mul__(self, other) is tried when your object is on the left side:

Python
a * b

__rmul__(self, other) is tried when your object is on the right side and the left object does not know how to multiply with it:

Python
b * a

Example:

Python
class Box:
def __mul__(self, other):
return "Box __mul__"

def __rmul__(self, other):
return "Box __rmul__"

x = Box()

print(x * 3) # calls __mul__
print(3 * x) # calls __rmul__

Python’s rule is roughly:

  1. Try left operand’s __mul__

  2. If it returns NotImplemented, try right operand’s __rmul__

This is especially useful for supporting expressions where your custom class appears on the right side of a built-in type, like 2 * custom_object.


All Questions From This Chapter    « Previously    Next »

No comments:

Post a Comment