# Python 中没有直接的静态变量概念,但可以通过多种方式实现类似的功能。
# 方法一:使用函数属性
def static_var(func):
setattr(func, 'counter', 0)
return func
@static_var
def my_function():
my_function.counter += 1
print(f"Function has been called {my_function.counter} times")
# 调用示例
my_function() # 输出: Function has been called 1 times
my_function() # 输出: Function has been called 2 times
# 方法二:使用类变量
class MyClass:
class_var = 0 # 类变量,相当于静态变量
def __init__(self):
MyClass.class_var += 1
print(f"Class variable value is now {MyClass.class_var}")
# 调用示例
obj1 = MyClass() # 输出: Class variable value is now 1
obj2 = MyClass() # 输出: Class variable value is now 2
# 方法三:使用 nonlocal 关键字(适用于嵌套函数)
def outer():
counter = 0
def inner():
nonlocal counter
counter += 1
print(f"Inner function has been called {counter} times")
return inner
inner_func = outer()
inner_func() # 输出: Inner function has been called 1 times
inner_func() # 输出: Inner function has been called 2 times
下一篇:python代码运行器
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站