questions about functions inside a function

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Mon Jul 16 16:15:40 CEST 2007


On Jul 16, 4:49 am, "fdu.xia... at gmail.com" <fdu.xia... at gmail.com>
wrote:

(snipped)

>
> 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?
>
> Thanks a lot!



The functools module, in Python 2.5 allows:

>>> import functools
>>> square = lambda i: i ** 2
>>> anon = [functools.partial(square, i) for i in range(4)]
>>> for f in anon:
...     print f()
...

--
Hope this helps,
Steven




More information about the Python-list mailing list