为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

温温酱 2019-06-23 16:02:11
函数中静态变量的Python等效值是什么?与这种C/C+代码相比,Python的惯用代码是什么?void foo(){     static int counter = 0;     counter++;     printf("counter is %d\n", counter);}具体来说,如何在函数级别实现静态成员,而不是类级别?把函数放入类中会改变什么吗?
查看完整描述

3 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

有点相反,但这应该有效:

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


查看完整回答
反对 回复 2019-06-23
?
森林海

TA贡献2011条经验 获得超2个赞

可以向函数添加属性,并将其用作静态变量。

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

无论如何,静态变量是相当罕见的,您应该为这个变量找到一个更好的位置,很可能在类中。


查看完整回答
反对 回复 2019-06-23
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

还可以考虑:

def foo():
    try:
        foo.counter += 1
    except AttributeError:
        foo.counter = 1

推理:

  • 大量丙酮(

    ask for forgiveness not permission)

  • 使用异常(只引发一次)而不是

    if

    分支(认为)

    止蚀

    例外情况)


查看完整回答
反对 回复 2019-06-23
  • 3 回答
  • 0 关注
  • 634 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信