On 11月26日, 下午8时48分, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > Alphones wrote: > > Hi all, > > > def getFunc(x): > > return lambda y : x + y > > > if __name__ == '__main__': > > todo = [] > > proc = getFunc(1) > > todo.append(lambda: proc(1)) > > proc = getFunc(2) > > todo.append(lambda: proc(1)) > > proc = getFunc(3) > > todo.append(lambda: proc(1)) > > > todo.append(lambda: getFunc(1)(1)) > > todo.append(lambda: getFunc(2)(1)) > > todo.append(lambda: getFunc(3)(1)) > > > for task in todo: > > print task() > > > ----------- > > the program outputs: > > 4 > > 4 > > 4 > > 2 > > 3 > > 4 > > in Python 2.6. > > is that excpected? > > Yes. Creating a lambda will close over the current *names* in the scope, > *not* their respective values. For that, you need to create a new scope - > e.g. by bindig the value to a argument of the lambda: > > lambdas = [] > for i in xrange(10): > lambda i=i : i ** 2 > > for l in lambdas: > l() > > Diez
thanks :D now I know what's wrong with my program. it is a little deferent from other script language. -- http://mail.python.org/mailman/listinfo/python-list