[英]python class Vector, change from 3dimension to ndimension
I made this class that computes some operations for 3d vectors, is there anyway I can change the code so that it computes the same operations but for vectors of any dimension n? 我创建了这个类来计算3d向量的一些操作,无论如何我是否可以更改代码以便它计算相同的操作但是对于任何维度的向量n?
import sys
class Vector:
def __init__(self,x,y,z):
self.x= x
self.y= y
self.z= z
def __repr__(self):
return "(%f,%f,%f)"%(self.x,self.y,self.z)
def __add__(self,other):
return (self.x+other.x,self.y+other.y,self.z+other.z)
def __sub__(self,other):
return (self.x-other.x,self.y-other.y,self.z-other.z)
def __norm__(self):
return (self.x**2+self.y**2+self.z**2)**0.5
def escalar(self,other):
return (self.x*other.x+self.y*other.y+self.z*other.z)
def __mod__(self,other):
return (self.x%other.x,self.y%other.y,self.z%other.z)
def __neg__(self):
return (-self.x,-self.y,-self.z)
As an example, for an dimensional vector, something like 作为一个例子,对于一个维度向量,像
class Vector:
def __init__(self, components):
self.components = components # components should be a list
def __add__(self, other):
assert len(other.components) == len(self.components)
added_components = []
for i in range(len(self.components)):
added_components.append(self.components[i] + other.components[i])
return Vector(added_components)
def dimensions(self):
return len(self.components)
would be possible. 是可能的。 Note that the
__add__
override returns a new Vector
instance, not a tuple
as in your case. 请注意,
__add__
覆盖返回一个新的Vector
实例,而不是您的情况下的tuple
。 Then adapt your other methods likewise. 然后同样适应你的其他方法。
There are more 'clever' ways of adding elements from two lists, into a third . 有更多“聪明”的方法可以将两个列表中的元素添加到第三个列表中 。 You should really not do it this way if performance is an issue though (or in any other case but an exercise, IMO).
如果性能是一个问题(或者在任何其他情况下,除了练习,IMO),你真的不应该这样做。 Look into numpy .
看看numpy 。
Use a list to store the coefficients rather than explicit variables. 使用列表存储系数而不是显式变量。 For negating, adding, subtracting etc. you just iterate over the lists.
对于否定,添加,减去等,您只需迭代列表。
In terms of initialisation, you need to use *args
for the input. 在初始化方面,您需要使用
*args
作为输入。 Have a look at this post for an explanation of how it works: https://stackoverflow.com/a/3394898/1178052 看一下这篇文章,了解它的工作原理: https : //stackoverflow.com/a/3394898/1178052
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.