Home >Backend Development >Python Tutorial >How Can I Simulate Static Variables in Python Functions?

How Can I Simulate Static Variables in Python Functions?

DDD
DDDOriginal
2024-12-16 19:03:16315browse

How Can I Simulate Static Variables in Python Functions?

Static Variables in Python Functions: Mimicking C/C

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.

Implementing Static Variables in Python Functions

To replicate the behavior of static variables inside Python functions, use the following approach:

<br>def foo():</p>
<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.

Decorator Approach

To enhance readability and move the initialization code to the top, one can use a decorator:

<br>def static_vars(**kwargs):</p>
<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)

Does Class Scope Affect Static Variables?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn