how to write function that returns function
Paul Graham
spam at bugbear.com
Fri May 17 18:28:06 EDT 2002
Thanks to several people who have sent me Python
"translations" for the following:
Scheme: (define (foo x)
(lambda (y) (set! x (+ x y))))
Perl: sub foo {
my ($n) = @_;
sub {$n += shift}
}
Here is a summary of the answers I got. This is
the closest thing to a direct translation:
def foo(n):
s = [n]
def bar(i):
s[0] += i
return s[0]
return bar
but it is considered ugly, and the canonical way to
do this seems to be by defining a class:
class foo:
def __init__(self, n):
self.n = n
def __call__(self, i):
self.n += i
return self.n
--pg
More information about the Python-list
mailing list