Equiv of C's static local vars in Py ?

Erik Max Francis max at alcyone.com
Sun Dec 1 17:28:09 EST 2002


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

> P.S. I know this can be done using OO in Py (by declaring a class that
> contains a member/field and then instantiating objects of that class);
> ...

That is probably the best approach for the kind of thing you want to do.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The perfection of innocence, indeed, is madness.
\__/ Arthur Miller
    CSBuddy / http://www.alcyone.com/pyos/csbuddy/
 A Counter-Strike server log file monitor in Python.



More information about the Python-list mailing list