【问题标题】:Using mutable function arguments to imitate C-like static variables in Python functions在 Python 函数中使用可变函数参数来模仿类 C 的静态变量
【发布时间】:2022-01-09 22:14:32
【问题描述】:

我想知道如何在 Python 中从 C 复制静态变量。我看到了很多与 Python 中的面向对象代码和可变默认参数的使用相关的帖子,但我只是想知道一个简单的过程示例。

这是我的 C 示例:

void static_variable(){
    static int x = 0;
    x++;
    printf("%d\n", x);
}

这是我的 Python 示例:

def static_variable(counter=[0]):
    counter[0] += 1
    print(counter[0])

这两个例子都有效,但是,我想知道在 Python 中使用这种方法是否会带来一些固有的危险 - 或者当您不知道可变参数时它是否只是危险?

【问题讨论】:

    标签: python c mutable static-variables


    【解决方案1】:

    在python中,函数是一等对象。这意味着它们可以具有属性。您可以简单地将属性用作“静态变量”。避免了可变默认值的陷阱,代码也更加简洁:

    def static_variable():
        # define function attribute
        if hasattr(static_variable, 'counter'):
            static_variable.counter += 1
        else:
            static_variable.counter = 1
        print(static_variable.counter)
    
    
    static_variable()
    static_variable()
    static_variable()
    

    结果:

    1
    2
    3
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      相关资源
      最近更新 更多