questions about functions inside a function

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Jul 15 18:42:41 EDT 2007


Jeremy Sanders a écrit :
> 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:
> 
> ...
> 
>>How to achieve this?
> 
> 
> This doesn't answer your question (others have), but another (perhaps
> clearer) way to do such things is something like
> 
> class MyFunc(object):
>   """A function object."""
>   def __init__(self, val):
>      self.val = val
> 
>   def __call__(self):
>      """Return value squared"""
>      return self.val**2
> 
> a = []
> for i in range(4):
>   a.append(MyFunc(i))
> 
> for f in a:
>   f()
> 

I wouldn't say it's "clearer" - at least in this concrete use case. And 
it takes more than just defining the __call__ method to have a fully 
function-like object (hint: try using a MyFunc instance as a method).



More information about the Python-list mailing list