Page 1 of 1

overload operator __rmul__ does not work

Posted: Fri Aug 19, 2016 4:11 pm
by stmfresser
i'm trying to test the overload operator __rmul__ on micropython, Unfortunately it does not work on micropython

Code: Select all

class foo:
    def __init__(self, data):
        self.data = data
    def __mul__(self, other):
        if type(other) in (int, float):
            return foo(self.data * other)
        else:
            return foo(self.data * other.data)
    def __rmul__(self, other):
        if type(other) in (int, float):
            return foo(self.data * other)
        else:
            return foo(self.data * other.data)

Code: Select all

if __name__ == '__main__':
    f1 = foo(10)
    f2 = foo(20)
    (f1*f2).data # 200
    (f1*50).data # 500
    (50*f1).data # it does not work on micropython

Code: Select all

>>> (50*f1).data                                                                
Traceback (most recent call last):                                              
  File "<stdin>", line 1, in <module>                                           
TypeError: unsupported types for __mul__: 'int', 'foo' 
I suppose __rmul__ has not implemented in micropython.

Does anyone know, how to solve it.

Re: overload operator __rmul__ does not work

Posted: Fri Aug 19, 2016 4:25 pm
by pfalcon
Sorry, none of the __r*__ methods are supported. MicroPython is intended to be a practical tool for (very) constrained systems, not a way to deal with abstractions-on-abstractions. In your case, an obvious way to resolve is:

Code: Select all

f1 = 10
50 * f1
If you really need to do that on objects, you of course can too:

Code: Select all

f1 = foo(10)
rmul(50, f1)

Re: overload operator __rmul__ does not work

Posted: Fri Aug 19, 2016 5:01 pm
by stmfresser
pfalcon wrote:Sorry, none of the __r*__ methods are supported.
Okay Thanks!