【问题标题】:Overload operator __mul__ python [duplicate]重载运算符__mul__ python [重复]
【发布时间】:2016-08-18 23:44:20
【问题描述】:

我正在尝试在此示例中实现 __mul__

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)

if __name__ == '__main__':
   f1 = foo(10)
   f2 = foo(20)

   (f1*f2).data # 200
   (f1*50).data # 500
   (50*f1).data # TypeError: unsupported operand type(s) for *: 'int' and 'instance'

但是它在50 * f1 不起作用。

有人知道怎么解决吗?

【问题讨论】:

    标签: python oop numpy operator-overloading


    【解决方案1】:

    为此,您需要__rmul__ 方法:

    调用这些方法来实现二进制算术运算(+、-、*、/、%、divmod()、pow()、**、>、&、^、|)与反射(交换)操作数。

    在你的情况下:

    class foo:
        def __init__(self, data):
            self.data = data
    
        def __mul__(self, other):
            # As before
    
        def __rmul__(self, other):
            # This will be called in the situation you brought up.
    

    【讨论】:

    • 在这种情况下,只需将__rmul__ = __mul__ 添加到类定义中就足够了(当然是在__mul__ 之后:-)
    • @mgilson 这是一个很好的观点 - 非常感谢。 (我必须承认我没有想到实现,只是如何调用方法)。
    猜你喜欢
    • 1970-01-01
    • 2010-12-28
    • 2014-02-25
    • 2015-06-20
    • 2011-10-27
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多