Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python静态变量

作者:噬血啸月   发布日期:2025-03-16   浏览:118

# 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

上一篇:jupyter配置python环境

下一篇:python代码运行器

大家都在看

python时间格式

python ord和chr

python中的yield

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站