Static Variables (fwd)
David Mertz, Ph.D.
mertz at gnosis.cx
Wed Apr 3 22:55:48 EST 2002
"Jim Jacobs" <jim.jacobs at jacobshome.com> wrote previously:
|Is it possible to simulate "C" style static variables in functions?
|In methods?
>From the other responses, it seems like a lot of users don't know the
"Python static trick." I use this moderately often... it is a slightly
strange spelling, but not hard once you learn it:
>>> def counter(msg, cnt=[0]):
... print cnt[0], msg
... cnt[0] += 1
...
>>> counter('first call')
0 first call
>>> counter('second call')
1 second call
>>> counter('third call')
2 third call
>>> counter('counter override', [37])
37 counter override
Anything passed with a mutable type default argument gets defined along
with the function itself. The value doesn't get redefined on calls
unless the caller explicitly forces it.
We-don't-need-no-stinkin-closures-ly yours, David...
--
mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i
gnosis _/_/ Postmodern Enterprises _/_/ s r
.cx _/_/ MAKERS OF CHAOS.... _/_/ i u
_/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s
More information about the Python-list
mailing list