【问题标题】:how can I overwrite __mul__ function in python [duplicate]如何在 python 中覆盖 __mul__ 函数 [重复]
【发布时间】:2018-12-08 17:12:57
【问题描述】:

我这样用python写了一个类

class Vector(object):
def __init__(self, coordinates):
    try:
        if not coordinates:
            raise ValueError
        self.coordinates = tuple(coordinates)
        self.dimension = len(coordinates)

    except ValueError:
        raise ValueError('The coordinates must be nonempty')

    except TypeError:
        raise TypeError('The coordinates must be an iterable')

def __add__(self,v):
    v1 = np.array(self.coordinates)
    v2 = np.array(v.coordinates)
    result = v1 + v2
    return result.tolist()

def __sub__(self, other):
    v1 = np.array(self.coordinates)
    v2 = np.array(other.coordinates)
    result = v1 - v2
    return result.tolist()

def __mul__(self, other):
    return other * np.array(self.coordinates)

def multiply(self,other):
    v = Decimal(str(other)) * np.array(self.coordinates)
    return v

def __str__(self):
    return 'Vector: {}'.format(self.coordinates)


def __eq__(self, v):
    return self.coordinates == v.coordinates

我想覆盖操作*,所以我可以实现如下功能:

3*Vector([1,2,3])=Vector([3,6,9])

所以我尝试了这样的代码:

    def __mul__(self, other):
    return other * np.array(self.coordinates)

但是,我很失望地发现此功能仅在以下情况下才有效

Vector([1,2,3])*3

如果我写了:

3*Vector([1,2,3])

上面写着:

TypeError: *: 'int' 和 'Vector' 的操作数类型不受支持

我怎样才能获得同时适用于3*Vector([1,2,3])Vector([1,2,3])*3 的函数?

非常感谢。

【问题讨论】:

  • 你需要定义__rmul__

标签: python overwrite operation


【解决方案1】:

这正是设计rmul 的原因。

class Vector(object):
    # ...
    def __rmul__(self, other):
       return self.__mul__(other)

【讨论】:

  • 虽然我已经实现了这段代码,但看起来你的代码比我的更优雅。我会拿你的代码。谢谢你的帮助。
【解决方案2】:

Vector([1,2,3])*3 有效,因为Vector()*3 表示“使用int 参数调用我的向量对象的__mul__() 函数”。

但是3*Vector([1,2,3]) 不起作用,因为它试图调用带有Vector 参数的int 对象的乘法函数:int 不知道你的Vector 类,所以它抛出一个错误。

您需要在Vector 上定义一个__rmul__() 函数来解决此问题。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 2019-01-04
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2016-02-04
相关资源
最近更新 更多