猿问

函数中静态变量的Python等效值是什么?

函数中静态变量的Python等效值是什么?

与这种C/C+代码相比,Python的惯用代码是什么?

void foo(){
    static int counter = 0;
    counter++;
    printf("counter is %d\n", counter);}

具体来说,如何在函数级别实现静态成员,而不是类级别?把函数放入类中会改变什么吗?


温温酱
浏览 635回答 3
3回答

潇湘沐

有点相反,但这应该有效:def foo():     foo.counter += 1     print "Counter is %d" % foo.counter foo.counter = 0如果希望计数器初始化代码位于顶部而不是底部,则可以创建一个装饰器:def static_var(varname, value):     def decorate(func):         setattr(func, varname, value)         return func    return decorate然后使用如下代码:@static_var("counter", 0)def foo():     foo.counter += 1     print "Counter is %d" % foo.counter它仍然需要您使用foo.不幸的是前缀。编辑(感谢奥尼):这个看起来更好: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     print "Counter is %d" % foo.counter

森林海

可以向函数添加属性,并将其用作静态变量。def myfunc():   myfunc.counter += 1   print myfunc.counter# attribute must be initializedmyfunc.counter = 0或者,如果不希望在函数外部设置变量,则可以使用hasattr()避免AttributeError例外:def myfunc():   if not hasattr(myfunc, "counter"):      myfunc.counter = 0  # it doesn't exist yet, so initialize it   myfunc.counter += 1无论如何,静态变量是相当罕见的,您应该为这个变量找到一个更好的位置,很可能在类中。

慕尼黑8549860

还可以考虑:def foo():     try:         foo.counter += 1     except AttributeError:         foo.counter = 1推理:大量丙酮(ask for forgiveness not permission)使用异常(只引发一次)而不是if分支(认为)止蚀例外情况)
随时随地看视频慕课网APP

相关分类

Python
我要回答