In C/C , functions can declare static variables to maintain state across function calls. Python, on the other hand, doesn't support static variables inside functions by default.
To replicate the behavior of static variables inside Python functions, use the following approach:
<br>def foo():</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">if not hasattr(foo, "counter"): foo.counter = 0 foo.counter += 1 print("Counter is", foo.counter)
Here, we check for the existence of the "counter" attribute inside the function. If it doesn't exist, we initialize it to 0. This initialization code is executed at the start of the first function call.
To enhance readability and move the initialization code to the top, one can use a decorator:
<br>def static_vars(**kwargs):</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate
@static_vars(counter=0)
def foo():
foo.counter += 1 print("Counter is", foo.counter)
Placing the function inside a class won't change the implementation of static variables. The static variables will still be function-specific, not class-specific.
The above is the detailed content of How Can I Simulate Static Variables in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!