473,545 Members | 2,779 Online

# Implementing Tuples with Named Items

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__(c ls, args)

setattr(supertu p, 'x', property(itemge tter(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? in my
itemgetter sample, the tuple is passed to itemgetter so it's obvious to see
what's going on. but in the supertup example, it isn't obvious to me.
thanks,

bryan

Jan 10 '06 #1
1 1336
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__(c ls, args)

setattr(supertu p, 'x', property(itemge tter(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? in my itemgetter sample, the tuple is passed to itemgetter
so it's obvious to see what's going on. but in the supertup example, it
isn't obvious to me.

Perhaps it helps to see the "intermedia te" steps between a standard property
class supertup(tuple) : .... def getx(self): return self[0]
.... x = property(getx)
.... gety = itemgetter(1)
.... y = property(gety)
.... z = property(itemge tter(2))
.... supertup.t = property(itemge tter(3))
setattr(supertu p, "u", property(itemge tter(4)))
t = supertup(range( 5))
t.u, t.t, t.z, t.y, t.x

(4, 3, 2, 1, 0)

class T:
def method(self): pass

and

class T:
pass

def method(self): pass
T.method = method

are both creating a class 'T' with a method 'method'. setattr() is only
needed if you don't know the attribute's name at compile time -- a method
is just and attribute of a class object.

Peter
Jan 10 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.