static variables?

Dennis Lee Bieber wlfraed at ix.netcom.com
Tue Nov 19 00:51:53 EST 2002


Josh fed this fish to the penguins on Monday 18 November 2002 08:18 pm:

> Hi guys,
> 
> I am a python newbie, and I am sure there is an easy answer but, Is
> there any equivalent to C's static variables in Python? If not, how

        Okay, the easy answer: No.

> can you have variables inside a function, that 'remember' their values
> between function calls?
>
        Complex answer 1: Create a python module containing initialized 
"variables" and the function (with the function declaring the variables 
"global"), import the module function.

Example:
,----[ /home/wulfraed/staticmod.py ]
| MyStatic = []
| 
| def MyFunc(a):
| global MyStatic
| MyStatic.append(a)
| print "MyFunc... MyStatic:", MyStatic

`----
,----[ /home/wulfraed/staticuser.py ]
| from staticmod import MyFunc
| 
| MyFunc(123)
| MyFunc('abc')
| MyFunc(10*3.33)
| 

`----
[wulfraed at beastie wulfraed]$ python staticuser.py
MyFunc... MyStatic: [123]
MyFunc... MyStatic: [123, 'abc']
MyFunc... MyStatic: [123, 'abc', 33.299999999999997]

        True, if you define two or more functions within the module, they both 
can access the variables defined within the module. I could have 
created MyFunc1 and MyFunc2, and had MyFunc2 perform the print 
statement.

        Complex answer 2: Create a python class; depending on coding you can 
have class-wide variables, or instance specific variables

,----[ /home/wulfraed/classy.py ]
| class cwide:
| MyVar = []
| def MyFunc(self,a):
| cwide.MyVar.append(a)
| def MyOut(self):
| print "Class Wide... MyVar...", cwide.MyVar
| 
| 
| class specific:
| def __init__(self):
| self.MyVar = []
| def MyFunc(self,a):
| self.MyVar.append(a)
| def MyOut(self):
| print "Instance Specific... MyVar...", self.MyVar
| 
| cw1 = cwide()
| cw2 = cwide()
| 
| cw1.MyFunc(123)
| cw2.MyFunc('ABC')
| cw1.MyFunc(('a', 'tuple'))
| cw2.MyOut()
| cw1.MyOut()
| 
| is1 = specific()
| is2 = specific()
| 
| is1.MyFunc(123)
| is2.MyFunc('ABC')
| is1.MyFunc(('a', 'tuple'))
| is2.MyOut()
| is1.MyOut()
| 
| 
| 
| 

`----
[wulfraed at beastie wulfraed]$ python classy.py
Class Wide... MyVar... [123, 'ABC', ('a', 'tuple')]
Class Wide... MyVar... [123, 'ABC', ('a', 'tuple')]
Instance Specific... MyVar... ['ABC']
Instance Specific... MyVar... [123, ('a', 'tuple')]

> Josh
> 
> 

-- 
 > ============================================================== <
 >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
 >      wulfraed at dm.net     |       Bestiaria Support Staff       <
 > ============================================================== <
 >        Bestiaria Home Page: http://www.beastie.dm.net/         <
 >            Home Page: http://www.dm.net/~wulfraed/             <




More information about the Python-list mailing list