questions about functions inside a function

Duncan Booth duncan.booth at invalid.invalid
Mon Jul 16 08:06:26 EDT 2007


"fdu.xiaojf at gmail.com" <fdu.xiaojf at gmail.com> wrote:

> What I want is, the value of i should be bounded to the anonymous
> function. And the output should like this:
> 
> for f in a:
>      print f()
> 0
> 1
> 4
> 9
> 
> How to achieve this?

Use default arguments when defining your function: default arguments are 
evaluated when the function is defined, bound arguments get the current 
value of the variable at the point when it is referenced during the call.

Also, since you give your function a name anyway ('b') you might as well 
use a named function as being clearer than using lambda:

>>> a = []
>>> for i in range(4):
	def b(i=i):
		return i**2
	a.append(b)

	
>>> for f in a:
	f()

	
0
1
4
9
>>> 



More information about the Python-list mailing list