Vector classes

Mark Dickinson dickinsm at gmail.com
Sun Apr 22 17:30:52 CEST 2007


On Apr 22, 8:33 am, Mizipzor <mizip... at gmail.com> wrote:
> With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do
> vec.vals[0] and vec.vals[1], which makes my eyes bleed.

If you add a __getitem__ method to the second vector class:

        def __getitem__(self, i):
                return self.vals[i]

then you can use vecs[0] instead of vec.vals[0].  But this vector
class has some other problems that you probably want to fix.  For
example, the __add__ method modifies the second argument:

>>> a = Vector([1, 2, 3])
[1, 2, 3]
>>> b = Vector([4, 5, 6])
[4, 5, 6]
>>> c = a + b
>>> print b.vals
[5, 7, 9]

Something like

        def __add__(self, other):
                return Vector(x + y for x, y in zip(self.vals,
other.vals))

might work better.  Similarly for the __sub__ method.

Have you considered using numpy?

Mark




More information about the Python-list mailing list