如何实现形式[1,2,3,4] + v的向量加法,其中v是向量,[1,2,3,4]是python中的列表?

时间:2018-05-15 15:08:27

标签: python

以下是该计划的代码: 我试图实现一个vector类,因为我在python中了解了运算符重载。我能够创建一个矢量类,它可以像列表一样使用像len(vector),vector1 + vector2(加法运算符重载)和减法这样的操作。但我发现了一个问题。这是程序的代码,我已经说明了下面的问题:

class vector:
"""Initialize Vector"""
def __init__(self,d):
    self.coords = [0]*d

def __len__(self):
    return len(self.coords)

def __getitem__(self, item): #Getting an item from a vector
    return self.coords[item]

def __setitem__(self, key, value):
    self.coords[key] = value

def __add__(self, other):
    if(len(self)!= len(other)):
        print("Don't add these too ! they are not same types :P")
    else:
        result = vector(len(self))
        for i in range(0,len(result)):
            result[i] = self[i] + other[i]
        return result
def __sub__(self, other):
    if(len(self) != len(other)):
        print("Dont subtract these two!")
    else:
        result = vector(len(self))
        for i in range(0,len(result)):
            result[i] = self[i] - other[i]
        return result

def __eq__(self, other):
    return self.coords == other.coords

def __ne__(self, other):
    return self.coords != other.coords

def __str__(self):
    return '<'+ str(self.coords)[1:-1] +'>'

print("Input for vector 1")
x = vector(2)
for i in range(0,len(x)):
    x[i] = int(input('Enter a number\n'))
print("Input for vector 2")
y = vector(2)
for i in range(0,len(y)):
    y[i] = int(input('Enter a number\n'))

z = x-y
print(str(x))
print("  +  ")
print(str(y))
print("  =  ")
print(str(z))

如果我添加一个矢量+列表但列表+矢量给出错误,它会起作用。我该如何实现另一个。

1 个答案:

答案 0 :(得分:1)

您想要实施__radd__。由于它应该与此处__add__执行相同的操作,因此您只需为其分配__add__

class vector:
  ...
  def __add__(self, other):
    if(len(self)!= len(other)):
      print("Don't add these too ! they are not same types :P")
    else:
      result = vector(len(self))
      for i in range(0,len(result)):
        result[i] = self[i] + other[i]
      return result

  __radd__ = __add__
  ...