how to write function that returns function

George Demmy gdemmy at layton-graphics.com
Wed May 15 13:49:06 EDT 2002


Correction:
George Demmy <gdemmy at layton-graphics.com> writes:

> spam at bugbear.com (Paul Graham) writes:
> 
> > Thanks to everyone who replied to my earlier question.  It seems
> > Python scope rules have changed recently, and my info was out of 
> > date.  I am still uncertain about a couple things though: there
> > seem to be some restrictions on what you can do with lexical
> > variables and also what you can put in a lambda.  Can some Python
> > expert tell me how you would express the Common Lisp
> > 
> > (defun foo (n) #'(lambda () (incf n)))
> > 
> > in Python?
> > 
> > Many thanks,  --pg
> 
> Here's one way:
> 
> class foo:
>   def __init__(self, n):
>     self.n = n
> 
>   def next(self):
>     self.n += 1
>     return self.n
> 
> def mkfoo(n):
>   f = foo(n)
>   return f.next
> 
> bar = foo(1)

bar = mkfoo(1)

> print bar(), bar(), bar()
> -> 2 3 4

G



More information about the Python-list mailing list