Implementing Tuples with Named Items
Fredrik Lundh
fredrik at pythonware.com
Tue Jan 10 01:01:51 EST 2006
Bryan wrote:
> in the python cookbook 2nd edition, section 6.7 (page 250-251), there a problem
> for implementing tuples with named items. i'm having trouble understanding how
> one of commands work and hope someone here can explain what exactly is going on.
> without copying all the code here, here is the gist of the problem:
>
> from operator import itemgetter
>
> class supertup(tuple):
> def __new__(cls, *args):
> return tuple.__new__(cls, args)
>
> setattr(supertup, 'x', property(itemgetter(0)))
>
> >>> t = supertup(2, 4, 6)
> >>> t.x
> >>> 2
>
>
> i understand what itemgetter does,
>
> >>> i = itemgetter(0)
> >>> i((2, 3, 4))
> >>> 2
> >>> i((4, 8, 12))
> >>> 4
>
> i understand what property does, and i understand what setattr does. i tested
> this problem myself and it works, but i can't understand how t.x evaluates to 2
> in this case. how does itemgetter (and property) know what tuple to use?
the missing piece in your puzzle is what's known as "descriptors":
http://users.rcn.com/python/download/Descriptor.htm
(property returns a descriptor, and the object machinery will use that
descriptor to control what happens when you access the 'x' attribute).
hope this helps!
</F>
More information about the Python-list
mailing list