如何重载加法、减法和乘法运算符,以便我们可以对大小不同或相同的两个向量进行加、减、乘操作?例如,如果向量的大小不同,我们必须能够根据最小的向量大小对这两个向量进行加、减或乘。
我已经创建了一个函数,允许您修改不同的向量,但现在我正在努力重载运算符,并且没有从哪里开始的线索。我将粘贴下面的代码。有什么想法吗?
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]
发布于 2013-12-10 23:50:36
您为类define the __add__
, __sub__
, and __mul__
方法,这就是方法。每个方法接受两个对象( +
/-
/*
)的操作数作为参数),并期望返回计算结果。
发布于 2017-11-28 01:02:52
这个问题的公认答案没有错,但我添加了一些快速片段来说明如何使用它。(请注意,您还可以“重载”该方法以处理多种类型。)
"""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
发布于 2013-12-10 23:47:16
docs有答案。基本上,当您添加或多个对象时,会在对象上调用一些函数,例如__add__
是普通的add函数。
https://stackoverflow.com/questions/20507745
复制相似问题