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

Mongryong Mongryong at sympatico.ca
Tue Feb 18 11:24:48 EST 2003


On Tue, 2003-02-18 at 01:57, Jp Calderone wrote:
> On Tue, Feb 18, 2003 at 12:49:18AM -0500, Mongryong wrote:
> > 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++.
> 
>   Default parameters are *evaluated* at function definition time.  This is
> ocassionally the same as "import time", but not always.

Geez..you're nit-picky.  You're right that 'function definition time' is
not always the same as 'module import time' - but for f*#k sakes, the
reason that I put 'import time' in quotes is to emphasize that its a
generalization and should be taken with carefully.  Other times, use
quotes because they can't think of the more 'definitive term' to use.  A
smart person, should be able to read my comments and come away with a
general understanding of what's going on - you can't spoon feed
everyone!

> 
>   Since we're discussing free functions, there is no memory saved in either
> Python or C.  If we were discussing static class members, C++ style, then a
> far more appropriate comparison is Python class attributes, which are
> "shared" amongst all instances of a class, just as C++'s static class
> members are.

I'm not too sure about C, but in C++, static method variables are
created at first call.  Hence, it saves 'global memory space' (notice
the quotes!) - that is, if the method is never called, memory is never
wasted for creating that 'long-lived' variable.  That's why it exists in
C++.  There's no namespace advantage in C++ by decalaring a variable
static in a method.








More information about the Python-list mailing list