User defined __mul__ method is not commutative

后端 未结 2 490
醉酒成梦
醉酒成梦 2020-12-29 21:26

I wrote a class to represent vectors in Python (as an exercise) and I\'m having problems with extending the built-in operators.

I defined a __mul__ meth

相关标签:
2条回答
  • 2020-12-29 21:59

    If you want commutativity for different types you need to implement __rmul__(). If implemented, it is called, like all __r*__() special methods, if the operation would otherwise raise a TypeError. Beware that the arguments are swapped:

    class Foo(object):
        def __mul_(self, other):
            ''' multiply self with other, e.g. Foo() * 7 '''
        def __rmul__(self, other):
            ''' multiply other with self, e.g. 7 * Foo() '''
    
    0 讨论(0)
  • 2020-12-29 22:07

    I believe you are looking for __rmul__

    0 讨论(0)
提交回复
热议问题