Static variables

Bruno Desthuilliers bruno.desthuilliers at websiteburo.com
Thu Jan 25 05:07:59 EST 2007


bearophileHUGS at lycos.com a écrit :
> Bruno Desthuilliers:
>> And this let you share state between functions:
>>
>> def make_counter(start_at=0, step=1):
>>    count = [start_at]
>>    def inc():
>>      count[0] += step
>>      return count[0]
>>    def reset():
>>      count[0] = [start_at]
>>      return count[0]
>>    def peek():
>>      return count[0]
>>
>>    return inc, reset, peek
>>
>> foo, bar, baaz = make_counter(42, -1)
>> print baaz()
>> for x in range(5):
>>     print foo()
>> print bar()
>> print baaz()
> 
> An interesting solution, I have never created such grouped clorures. 

It's a common idiom in some functional languages.

> I
> don't know if this solution is better than a class with some class
> attributes plus some class methods...

It's somewhat equivalent, but in Python, I'd surely use a class instead !-)



More information about the Python-list mailing list