How can I do this (from Perl) in Python? (closures)
Nick Craig-Wood
nick at craig-wood.com
Thu Dec 4 05:30:47 EST 2008
excord80 at gmail.com <excord80 at gmail.com> wrote:
> I just came across http://www.perl.com/pub/a/2002/05/29/closure.html
> and wanted to try the "canonical example of closures" in Python. I
> came up with the following, but it fails:
>
> def make_counter(start_num):
> start = start_num
> def counter():
> start += 1
> return counter
>
> from_ten = make_counter(10)
> from_three = make_counter(3)
>
> print from_ten() # 10
> print from_ten() # 11
> print from_three() # 3
> print from_ten() # 12
> print from_three() # 4
>
> The error message is: "UnboundLocalError: local variable 'start'
> referenced before assignment". The same thing happens if I omit start
> and just use start_num directly.
>
> How can I do it in Python?
With a class is the best way IMHO.
class make_counter(object):
def __init__(self, start_num):
self.x = start_num
def __call__(self):
x = self.x
self.x += 1
return x
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list