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

How Can I Simulate Static Function Variables in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 17:56:11165browse

How Can I Simulate Static Function Variables in Python?

Python Equivalent of Static Function Variables

Problem:
How does Python implement static variables within functions, similar to C/C 's static member variables defined at the function level?

Answer:

In Python, there is no direct equivalent for static variables within functions. However, a similar functionality can be achieved using a combination of nested functions and closures:

def foo():
    def counter():
        if not hasattr(foo, "counter_value"):
            foo.counter_value = 0
        foo.counter_value += 1
        return foo.counter_value
    return counter

Here, the function foo() defines a nested function counter(). The outer function foo() serves as a closure for counter(), providing it with an isolated namespace.

To access and increment the counter, you would call:

counter = foo()
counter()  # Initializes the counter
counter()  # Increments the counter

Decorator Approach:

Another approach is to use a decorator to create a static variable:

def static_vars(**kwargs):
    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
    return foo.counter

This syntax allows you to initialize and access the static variable more conveniently, but it requires using the foo. prefix.

The above is the detailed content of How Can I Simulate Static Function Variables in Python?. 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