Col*_*lue 34 python overriding operator-keyword
所以,我有一个自定义类,它具有__mul__与int一起使用的函数.然而,在我的程序中(在库中),它被反过来调用,即我的类2 * x在哪里x.有没有办法可以让它使用我的__mul__功能呢?
Kar*_*tel 36
只需将以下内容添加到类定义中即可:
__rmul__ = __mul__
Run Code Online (Sandbox Code Playgroud)
Cat*_*lus 26
实施__rmul__也.
class Foo(object):
def __mul__(self, other):
print '__mul__'
return other
def __rmul__(self, other):
print '__rmul__'
return other
x = Foo()
2 * x # __rmul__
x * 2 # __mul__
Run Code Online (Sandbox Code Playgroud)