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

sjdevnull at yahoo.com sjdevnull at yahoo.com
Thu Mar 15 12:47:19 EDT 2007


Marc 'BlackJack' Rintsch wrote:
> In <1173942572.130747.228410 at l77g2000hsb.googlegroups.com>, dmitrey wrote:
>
> > Thank you in advance,
>
> For what?  Hint: Don't "hide" the question in the subject line.
>
> I don't know MATLAB's `persistent` but I know that ``static`` in C++ can
> be used in different places with different meanings.
>
> It seems you are asking questions how to translate some constructs from
> other languages 1:1 into Python.  Without context this may lead you to
> programming some other language in Python, resulting in fighting the
> language because you don't use "pythonic" idioms to solve your problems.
>
> C++-static function's names on module level should start with an
> underscore:
>
> def _i_am_not_meant_to_be_public():
>     pass
>
> It's a naming convention for things that are considered internal.
>
> C++-static class members are class attributes in Python:
>
> class Spam(object):
>     i_am_a_class_attribute = 42
>
>     def __init__(self):
>         self.i_am_an_instance_attribute = 'Viking'
>
> And C++static local variables don't exist in Python.  There are ways to
> emulate them with mutable default arguments, but that's at least
> debatable.  Use a class instead.

If you must, function attributes emulate static:
def  myfunc():
   myfunc.foo += 1
    return myfunc.foo
myfunc.foo=0 #initialize the value near the function definition

>>> print  myfunc()
1
>>> print  myfunc()
2
etc

But it's usually a bad idea to use this.  function attributes are
better reserved for information about the function itself (similar to
docstrings).




More information about the Python-list mailing list