Scott Lamb wrote: > I'm trying to dynamically generate class methods which have access to > some state passed in at creation time. (Basically as a workaround to > twisted's trial not having a way to dynamically add stuff. Plain > unittest seems to have TestSuite, but the trial runner doesn't know > about it.) > > My first attempt might better illustrate this - > > class Foo: > def generalized(self, ctx): > print 'my ctx is %r' % ctx > > for i in ['a','b','c']: > setattr(Foo, i, lambda self: self.generalized(i)) > > foo = Foo() > foo.a() > foo.b() > foo.c() > > but this prints "my ctx is c" three times; I'd hoped for a, b, c, of > course.
def build(j): setattr(Foo, j, lambda self: self.generalized(j)) for i in ["a","b","c"]: build(i) Each call of the the build function creates its own cell "j" that the lambda references. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list