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

How Can I Simulate Static Variables in Python Functions?

DDD
Release: 2024-12-16 19:03:16
Original
213 people have browsed it

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>
<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)
Copy after login

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>
<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
Copy after login

@static_vars(counter=0)
def foo():

foo.counter += 1
print("Counter is", foo.counter)
Copy after login

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!

source:php.cn
Previous article:How Can I Pretty-Print Entire Pandas DataFrames and Series in Python? Next article:How Can I Bin a Pandas DataFrame Column and Count Values in Each Bin?
Statement of this Website
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template