static variables?

Michele Simionato mis6 at pitt.edu
Tue Nov 19 12:37:48 EST 2002


"Josh" <jslmaslk at earthlink.net> wrote in message news:<cYiC9.5388$fY3.575010 at newsread2.prod.itd.earthlink.net>...
> 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 can you have
> variables inside a function, that 'remember' their values between function
> calls?
> 
> Josh

A simple trick to simulate static variables by passing an optional
mutable object is the following:

def f(x,i=[0]): # i[0] is the "static" variable
    i[0]+=1
    return x+i[0]

print f(0),f(0),f(0) #--> 1,2,3


See 

http://www-106.ibm.com/developerworks/linux/library/l-pycon.html?dwzone=linux

for more.

-- 
Michele Simionato - Dept. of Physics and Astronomy
210 Allen Hall Pittsburgh PA 15260 U.S.A.
Phone: 001-412-624-9041 Fax: 001-412-624-9163
Home-page: http://www.phyast.pitt.edu/~micheles/



More information about the Python-list mailing list