Equiv of C's static local vars in Py ?
laotseu
bdesth at nospam.free.fr
Wed Dec 4 22:27:23 EST 2002
Ben Wolfson wrote:
> On Sun, 01 Dec 2002 14:28:09 +0000, Erik Max Francis wrote:
>
>
>>Az Tech wrote:
>>
>>
>>>This function f retains the value of call_count between successive
>>>calls to it - so each time it is called, the value for call_count
>>>printed out will be one more than the last one.
>>>
>>>Can this be done in Python and if so, how ?
>>
>>This was just asked and answered a few days ago. Python doesn't have
>>any notion of a static variable in the sense that you mean here. If you
>>want, you can simply use a global:
>>
>> _Count = 0
>> def f():
>> global _Count
>> _Count += 1
>> print "f been called %d times" % _Count
>
>
> I didn't read the other threads on this subject, but recent Pythons have
> what I think is a more graceful way:
>
>
>>>>def f():
>>>
> f.count += 1
> print 'f has been called %d times' % (f.count)
>
>
>
>>>>f.count = 0
>>>>f()
>>>
> f has been called 1 times
>
>>>>f()
>>>
> f has been called 2 times
>
>
> You still have to initialize the variable outside the function-definition
> block, but it's more obviously intended to go with that function alone.
>
Yop ! I didn't know that one !
What a wonderful world !
Laotseu
More information about the Python-list
mailing list