重载加法,减法和乘法运算符

use*_*014 16 python class vector operators

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

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

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

jwo*_*der 26

定义__add__,__sub__以及__mul__对类的方法,这是怎么样.每个方法都将两个对象(+/ -/ 的操作数*)作为参数,并期望返回计算结果.

  • @ user3014014:否;是`def __add __(self,y)`。“ self”是“ +”的左操作数。 (3认同)

cmd*_*cmd 7

docs有答案.基本上,当你添加或多个等时,会有一些函数被调用,例如__add__正常的添加函数.


bin*_*ate 6

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


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