函数中静态变量的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

森林海
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

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
def foo(): try: foo.counter += 1 except AttributeError: foo.counter = 1
大量丙酮( ask for forgiveness not permission
)使用异常(只引发一次)而不是 if
分支(认为) 例外情况)
添加回答
举报
0/150
提交
取消