Is there a more elegant way to do this?
peter at engcorp.com
Mon Jun 28 15:20:12 CEST 2004
> Is there a more elegant way of doing this?
> I would like to have the arguments to pack
> automatically taken from lst.
> def pack(self):
> lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \
> 'green', 'blue', 'size', 'rotate', 'translucency']
> return struct.pack('<IIIiiiBBBHHH', \
> self.id, self.parent, self.number, \
> self.x, self.y, self.z, \
> self.red, self.green, self.blue, \
> self.size, self.rotate, self.translucency)
The following is perhaps the most easily maintainable
of the responses *if* you expect things to change at
all. If the whole thing is very stable, the explicit
approach, as Peter Otten says, might be preferred.
args = ('Iid Iparent Inumber ix iy iz Bred Bgreen Bblue '
'Hsize Hrotate Htranslucency')
lst = zip(*[(x,x[1:]) for x in s.split()])
return struct.pack('<' + ''.join(lst),
*[getattr(self, n) for n in lst])
It's also easily the most inscrutable of the responses... but
if you have to do this sort of thing in various places in your
code, it makes a nice utility function.
More information about the Python-list