如何在 python 中覆盖 __mul__ 函数

che*_*ang 3 python overwrite operation

我用 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
Run Code Online (Sandbox Code Playgroud)

我想覆盖该操作*,这样我就可以实现如下功能:

3*Vector([1,2,3])=Vector([3,6,9])
Run Code Online (Sandbox Code Playgroud)

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

    def __mul__(self, other):
    return other * np.array(self.coordinates)
Run Code Online (Sandbox Code Playgroud)

然而,我很失望地发现这个功能只有在以下情况下才有效

Vector([1,2,3])*3
Run Code Online (Sandbox Code Playgroud)

如果我写:

3*Vector([1,2,3])
Run Code Online (Sandbox Code Playgroud)

它说:

类型错误:* 不支持的操作数类型:“int”和“Vector”

3*Vector([1,2,3])如何获得同时适用于和 的函数Vector([1,2,3])*3?

太感谢了。

Ric*_*lis 5

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

但3*Vector([1,2,3])不起作用,因为它尝试使用int参数调用对象的乘法函数Vector:int不知道您的Vector类,因此它会抛出错误。

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