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
Release: 2024-12-04 17:56:11
Original
169 people have browsed it

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

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

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

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template