【发布时间】:2011-10-17 01:59:09
【问题描述】:
所以,我有一个自定义类,它有一个__mul__ 函数,可以与整数一起使用。但是,在我的程序(在库中)中,它被反过来调用,即 2 * x 其中 x 属于我的班级。有没有办法让它使用我的__mul__ 函数?
【问题讨论】:
标签: python overriding operator-keyword
所以,我有一个自定义类,它有一个__mul__ 函数,可以与整数一起使用。但是,在我的程序(在库中)中,它被反过来调用,即 2 * x 其中 x 属于我的班级。有没有办法让它使用我的__mul__ 函数?
【问题讨论】:
标签: python overriding operator-keyword
只需将以下内容添加到类定义中就可以了:
__rmul__ = __mul__
【讨论】:
同时实现__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__
【讨论】:
x * x 给出:<__main__.Foo at 0x7f8604be1e50> 如何处理这个?