繁体   English   中英

python类Vector,从3dimension更改为ndimension

[英]python class Vector, change from 3dimension to ndimension

我创建了这个类来计算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)

作为一个例子,对于一个维度向量,像

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)

是可能的。 请注意, __add__覆盖返回一个新的Vector实例,而不是您的情况下的tuple 然后同样适应你的其他方法。

有更多“聪明”的方法可以将两个列表中的元素添加到第三个列表中 如果性能是一个问题(或者在任何其他情况下,除了练习,IMO),你真的不应该这样做。 看看numpy

使用列表存储系数而不是显式变量。 对于否定,添加,减去等,您只需迭代列表。

在初始化方面,您需要使用*args作为输入。 看一下这篇文章,了解它的工作原理: https//stackoverflow.com/a/3394898/1178052

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM