Under what circumstances are __rmul__ called?

后端 未结 3 1739
感情败类
感情败类 2020-12-02 13:15

Say I have a list l. Under what circumstance is l.__rmul__(self, other) called?

I basically understood the documentation, but I would also

3条回答
  •  温柔的废话
    2020-12-02 13:43

    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.

提交回复
热议问题