Static (local) Method Variables (was: can someone explain?)

Mongryong Mongryong at sympatico.ca
Tue Feb 18 00:49:18 EST 2003


Some people have asked about how to do static (local) method variables
(like in C/C++).  Apparently, there is a simple way to do it via default
function parameters.  Consider the following example:

def append(x, list=[]):
	list += x
	return list

>>> append(1)
[1]
>>> append(2)
[1,2]

Now, the above isn't really a 'true' immitation of C/C++'s static method
variable implementation.  A true static method variable is created at
first call.  In Python, default parameters are created at 'import
time'.  Hence, you're not saving any 'memory space' like you would in
C/C++.

Note, the above only works for referencable objects and not built in
types like 'ints'.









More information about the Python-list mailing list