How to create a list of functions depending on a parameter?

Luis Zarrabeitia kyrie at uh.cu
Wed May 27 13:00:08 EDT 2009


On Tuesday 26 May 2009 05:00:14 am Paul Rudin wrote:
>
> class Foo(object):
>
>     def __init__(self, pos):
>         self.pos = pos
>
>     def __call__(self, arg):
>         return self.pos + arg
>
> f = [Foo(x) for x in range(10)]

Or, without the class:

In [1]: def get_incrementor(n):
   ...:     def inc(x):
   ...:         return x+n
   ...:     return inc
   ...:

In [3]: fs = [get_incrementor(n) for n in xrange(10)]

In [4]: fs[2](1)
Out[4]: 3




-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie



More information about the Python-list mailing list