what are Python equivalent to MATLAB persistent or C++ static?

sturlamolden sturlamolden at yahoo.no
Thu Mar 15 18:29:37 EDT 2007


On Mar 15, 8:09 am, "dmitrey" <open... at ukr.net> wrote:
> Thank you in advance,
> Dmitrey

First, "static" can mean at least three different things in C++:

static int myvar1;

void foobar() {
   static int myvar2;
}

class foobar {
   static int myvar3;
}

I assume you are thinking about the second case above - a static
variable inside a function. You can achieve this by binding an
attribute to the function, use a closure, or declare a class
callable.

def foobar1():
   if not 'mystatic' in dir(foobar): foobar.mystatic = 0
   foobar.mystatic += 1
   return foobar.mystatic

def foobar2():
   mystatic = 0
   def closure():
      mystatic += 1
      return mystatic
   return closure

class foobar3:
   mystatic = 0
   def __call__():
      foobar.mystatic += 1
      return foobar.mystatic

Usage:

for i in xrange(0,10): print foobar1()

myclosure = foobar2()
for i in xrange(0,10): print myclosure()

myfoobar3 = foobar3()
for i in xrange(0,10): print myfoobar3()












More information about the Python-list mailing list