Functionality like local static in C
Dieter Maurer
dieter at handshake.de
Thu Apr 14 13:43:54 EDT 2022
Cecil Westerhof wrote at 2022-4-14 17:02 +0200:
>In C when you declare a variable static in a function, the variable
>retains its value between function calls.
>The first time the function is called it has the default value (0 for
>an int).
>But when the function changes the value in a call (for example to 43),
>the next time the function is called the variable does not have the
>default value, but the value it had when the function returned.
>Does python has something like that?
In "C" a variable designates a storage location; assignment to
the variable changes the stored value.
In "Python" a variable designates an object.
Assignments to the variable do not change the object but
the association variable-object.
The im|mutability of the object determines whether the object
can or cannot have different values.
Mutable objects can behave similar to storage locations,
e.g.
class StaticVariable:
def __init__(self, v): self.v = v
def set(self, v): self.v = v
def get(self): return self.v
static_emul = StaticVariable(...)
def f(...):
...
static_emul.set(...)
...
More information about the Python-list
mailing list