static keyword

Yermat loic at fejoz.net
Thu Apr 29 10:57:47 EDT 2004


Peter Hansen wrote:
> Nick Jacobson wrote:
> 
>> I believe the following "static" command would be useful in Python.

I do not ! Static variable are like global...

> [snip]
> 
>> Just like in C, the variables i and firstcall are only assigned the
>> first time foo() is called.  To get this effect currently, one could
>> use default arguments or wrapping the whole thing in a class.  Both of
>> these solutions seem like hacks, the above method IMO is more
>> Pythonic. :)

or use global with carefully choosed name...


> class HasState:
>     def __init__(self):
>         self.firstCall = True
>         self.i = [10, 11]
> 
>     def foo(self):
>         if self.firstCall:
>             print "First pass"
>             self.firstCall = False
>         self.i[0] += 1
>         print self.i[0]
> 
> obj = HasState()
> obj.foo()
> obj.foo()

Like this solution because most of the timethis is not really static 
variable that we want but a per context "static" variable.

Anyway, if this is really static variable that you want,
what about this : 8-)

 >>> i = [10 ,11]
 >>> firstcall = True
 >>>
 >>> def foo():
...     global i
...     global firstcall
...     if firstcall:
...             print "First pass"
...             firstcall = False
...     i[0] += 1
...     print i[0]
...
 >>> foo()
First pass
11
 >>> foo()
12

-- 
Yermat




More information about the Python-list mailing list