python - 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 .
解决方案
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__
...
推荐阅读
- java - 如何从头开始安装这个 Maven 依赖项?
- jquery - Angular 6 - 显示模式时滚动到顶部
- python - scikit-learn:RandomForestRegressor:训练时的ValueError
- python - 我不能使用不同的函数来提取数据并从 beautifulsoup python 中过滤掉
- android - 如何检查用户是否触摸了任何东西?
- ios - 为什么 AVAssetWriter 创建的文件大小为 0?
- asp.net-core - 在 Visual Studio 之外的 .NET Core 中获取所有使用的 NuGet 包的许可证信息
- swift - 在 Alamofire 中上传具有深度参数的图像
- postgresql - 如何使用变量作为别名
- flutter-dependencies - pubspec.yaml 第 55 行第 4 列出错:解析块映射时需要一个键。字体: