- Code: Select all
#!/usr/bin/python
# -*- coding: utf-8 -*-
def cb(n):
print "cb invoked using:"
print n
# Make closures
farr=[None]*3
for i in xrange(0,3):
farr[i]=lambda: cb(i)
farr[0]()
My intent is to store into the array farr 3 anonymous functions. Each should call my function cb, but with parameters 0, 1 or 2 respectively. In particular, I expected farr[0] to have stored a function lambda: cb(i) with i bound to zero. However, farr[0]() outputs 2, not 0.
Well, I thought, maybe i is passed by reference, and hence all three anonymous functions access the same copy of i, and I therefore get the last value for i. But how can I then bind the three functions to different parameters?