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:
Pythona * 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:
Pythonb * a
Example:
Pythonclass 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:
-
Try left operand’s
__mul__ -
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