Say I have a list l
. Under what circumstance is l.__rmul__(self, other)
called?
I basically understood the documentation, but I would also
Binary operators by their nature have two operands. Each operand may be on either the left or the right side of an operator. When you overload an operator for some type, you can specify for which side of the operator the overloading is done. This is useful when invoking the operator on two operands of different types. Here's an example:
class Foo(object):
def __init__(self, val):
self.val = val
def __str__(self):
return "Foo [%s]" % self.val
class Bar(object):
def __init__(self, val):
self.val = val
def __rmul__(self, other):
return Bar(self.val * other.val)
def __str__(self):
return "Bar [%s]" % self.val
f = Foo(4)
b = Bar(6)
obj = f * b # Bar [24]
obj2 = b * f # ERROR
Here, obj
will be a Bar
with val = 24
, but the assignment to obj2
generates an error because Bar
has no __mul__
and Foo
has no __rmul__
.
I hope this is clear enough.