automatically assigning names to indexes

Peter Otten __peter__ at web.de
Tue Jul 12 02:31:01 EDT 2005


simonwittber at gmail.com wrote:

> 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?
 
>>> class Vector(tuple):
...     x = property(lambda self: self[0])
...     y = property(lambda self: self[1])
...     z = property(lambda self: self[2])
...
>>> Vector("abc")
('a', 'b', 'c')
>>> Vector("abc").z
'c'
>>> Vector("abc")[2]
'c'

However, no magic is involved.

Peter




More information about the Python-list mailing list