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!