首页 > 解决方案 > How can i implement Vector addition for the form [1,2,3,4] + v where v is vector and [1,2,3,4] is a list in python?

问题描述

Here is the code for the program: I tried to implement a vector class as i learned about operator overloading in python. I was able to make a vector class which can be used much like a list with operations like len(vector) , vector1 + vector2 (addition operator overloading) and subtraction . But i found a problem. Here is the code of the program and i have stated the problem below :

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))

It works if i add a vector + list but list + vector gives an error. How can i implement the other .

标签: python

解决方案


You want to implement __radd__. Since it should do the same thing as __add__ here, you can just assign __add__ to it:

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__
  ...

推荐阅读