Help with dynamic attributes.
fredrik at pythonware.com
Mon Jan 9 09:50:24 EST 2006
> class foo(object):
> def __init__(self, list_of_lists):
> self.lol = list(list_of_lists)
> for i in range(len(list_of_lists)):
> exec 'self.x%d = self.lol[%d]' % (i, i)
> self.shape = tuple(len(item) for item in self.lol)
generator expressions are anonymous functions, and the "self" in that line
is a free variable (that is, it belongs to an outer scope). Python uses static
analysis to identify free variables, and that doesn't mix well with exec.
> Any better way to get the same attributes I got with the exec statement?
use setattr(self, name, value)
More information about the Python-list