How can I do this (from Perl) in Python? (closures)

James Stroud jstroud at mbi.ucla.edu
Thu Dec 4 09:59:00 CET 2008


excord80 at gmail.com wrote:
> 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?

Since no one has suggested it:

class make_counter(object):
   def __init__(self, i):
     self.i = i
   def __call__(self):
     i = self.i
     self.i += 1
     return i

James


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com



More information about the Python-list mailing list