简体   繁体   中英

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?

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. 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). Look into 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. Have a look at this post for an explanation of how it works: https://stackoverflow.com/a/3394898/1178052

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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