automatically assigning names to indexes

George Sakkis gsakkis at rutgers.edu
Tue Jul 12 13:53:31 CEST 2005


<simonwittber at gmail.com> wrote:

> I know its been done before, but I'm hacking away on a simple Vector
> class.
>
> class Vector(tuple):
>     def __add__(self, b):
>         return Vector([x+y for x,y in zip(self, b)])
>     def __sub__(self, b):
>         return Vector([x-y for x,y in zip(self, b)])
>     def __div__(self, b):
>         return Vector([x/b for x in self])
>     def __mul__(self, b):
>         return Vector([x*b for x in self])
>
> I like it, because it is simple, and can work with vectors of any
> size...
>
> However, I'd like to add attribute access (magically), so I can do
> this:
>
> v = Vector((1,2,3))
> print v.x
> print v.y
> print v.z
>
> as well as:
>
> print v[0]
> print v[1]
> print v[2]
>
> Has anyone got any ideas on how this might be done?

And what should happen for vectors of size != 3 ? I don't think that a
general purpose vector class should allow it; a Vector3D subclass would
be more natural for this.

George




More information about the Python-list mailing list