重载加减乘运算符

37

如何重载加法、减法和乘法运算符,以便我们可以添加、减去和相乘两个大小不同或相同的向量?例如,如果向量的大小不同,我们必须能够按照最小向量大小添加、减去或相乘两个向量。

我已经创建了一个函数,允许您修改不同的向量,但现在我正在努力重载运算符,并且不知道从哪里开始。我将在下面粘贴代码。有什么想法吗?

def __add__(self, y):
    self.vector = []
    for j in range(len(self.vector)):
        self.vector.append(self.vector[j] + y.self.vector[j])
    return Vec[self.vector]
3个回答

48

你需要为这个类定义 __add____sub____mul__方法。每个方法都需要接受两个对象(即+/-/*的操作数)作为参数,并且应该返回计算结果。


1
@user3014014:和你定义其他方法的方式一样,只需将它们放在类定义中即可。 - jwodder
像这样 def __add__(self, x, y) 会有两个参数吗? - user3014014
4
不;它是 def __add__(self, y)self+ 的左操作数。 - jwodder
你可能想看一下 fractions 模块。注意顶部的源链接。这是因为它旨在用作编写自己的数字类的示例代码。它看起来可能比你需要的要复杂得多,但如果你实际上想要模拟所有运算符,并能够使用标量值(所以 myvec * 22 * myvec 可以工作),等等,那么“复杂”的方式实际上比复制和粘贴所有琐碎的部分几十次更容易。 - abarnert
1
而要进行除法运算,请使用__truediv__。更多信息请参见https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types。 - cowlinator
显示剩余4条评论

18

这个问题的接受答案没有错,但我会添加一些快速代码片段来说明如何使用它。(请注意,您也可以“重载”该方法以处理多种类型。)


"""Return the difference of another Transaction object, or another 
class object that also has the `val` property."""

class Transaction(object):

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other.val


buy = Transaction(10.00)
sell = Transaction(7.00)
print(buy - sell)
# 3.0

"""Return a Transaction object with `val` as the difference of this 
Transaction.val property and another object with a `val` property."""

class Transaction(object):

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return Transaction(self.val - other.val)


buy = Transaction(20.00)
sell = Transaction(5.00)
result = buy - sell
print(result.val)
# 15

"""Return difference of this Transaction.val property and an integer."""

class Transaction(object):

    def __init__(self, val):
        self.val = val

    def __sub__(self, other):
        return self.val - other


buy = Transaction(8.00)
print(buy - 6.00)
# 2

如何重载方法以接受多种类型? - cikatomo

7

文档中有答案。基本上,在对对象进行加法或乘法等运算时,会调用一些函数。例如,__add__是普通的加法函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接