[BangPypers] BangPypers Digest, Vol 6, Issue 8

Pythonic pythonic at gmail.com
Mon Feb 18 13:40:47 CET 2008


Siddharta wrote:
> Pythonic wrote:
>   
>> * 2. Best solution (Pythonic)*
>>
>>   
>>     
>>>>> import itertools
>>>>> c = itertools.count(9)
>>>>> c.next()
>>>>>         
>>>>>           
>> 9
>>   
>>     
>>>>> c.next()
>>>>>         
>>>>>           
>> 10
>>   
>>     
>
> +1 Pythonic: itertools is the way to go
>
> But if you really want to implement it yourself, you need to do 
> something like this -
>
>  >>> class ns: pass
> ...
>  >>> def make_incr(start):
> ...     v = ns()
> ...     v.count = start
> ...     def incr():
> ...             v.count += 1
> ...             return v.count
> ...     return incr
> ...
>  >>> i = make_incr(5)
>  >>> i()
> 6
>  >>> i()
> 7
>
> It's more complex than if you did it in a functional language because of 
> limitations on lambda and accessing variables in nested scopes.
>
> --
> Siddharta Govindaraj
> _______________________________________________
>
>   
ah well, could not stop my self. More OO (?) way

>>> class Incrementer(object):
...     def __init__(self, n=0): self.n = n
...     def __call__(self):
...             self.n += 1
...             return self.n
...

>>> i = Incrementer()
>>> i()
1
>>> i()
2



More information about the BangPypers mailing list