When Python attempts to multiply two objects, it first tries to call the left object’s
__mul__() method. If the left object doesn’t have a
__mul__() method (or the method returns
NotImplemented, indicating it doesn’t work with the right operand in question), then Python wants to know if the right object can do the multiplication. If the right operand is the same type as the left, Python knows it can’t, because if the left object can’t do it, another object of the same type certainly can’t either.
If the two objects are different types, though, Python figures it’s worth a shot. However, it needs some way to tell the right object that it is the right object in the operation, in case the operation is not commutative. (Multiplication is, of course, but not all operators are, and in any case
* is not always used for multiplication!) So it calls
__rmul__() instead of
As an example, consider the following two statements:
print "nom" * 3 print 3 * "nom"
In the first case, Python calls the string’s
__mul__() method. The string knows how to multiply itself by an integer, so all is well. In the second case, the integer does not know how to multiply itself by a string, so its
NotImplemented and the string’s
__rmul__() is called. It knows what to do, and you get the same result as the first case.
Now we can see that
__rmul__() allows all of the string’s special multiplication behavior to be contained in the
str class, such that other types (such as integers) do not need to know anything about strings to be able to multiply by them. A hundred years from now (assuming Python is still in use) you will be able to define a new type that can be multiplied by an integer in either order, even though the
int class has known nothing of it for more than a century.
By the way, the string class’s
__mul__() has a bug in some versions of Python. If it doesn’t know how to multiply itself by an object, it raises a
TypeError instead of returning
NotImplemented. That means you can’t multiply a string by a user-defined type even if the user-defined type has an
__rmul__() method, because the string never lets it have a chance. The user-defined type has to go first (e.g.
Foo() * 'bar' instead of
'bar' * Foo()) so its
__mul__() is called. They seem to have fixed this in Python 2.7 (I tested it in Python 3.2 also), but Python 2.6.6 has the bug.