函數(shù)中靜態(tài)變量的Python等效值是什么?與這種C/C+代碼相比,Python的慣用代碼是什么?void foo(){
static int counter = 0;
counter++;
printf("counter is %d\n", counter);}具體來說,如何在函數(shù)級(jí)別實(shí)現(xiàn)靜態(tài)成員,而不是類級(jí)別?把函數(shù)放入類中會(huì)改變什么嗎?
3 回答

瀟湘沐
TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
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貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
def foo(): try: foo.counter += 1 except AttributeError: foo.counter = 1
大量丙酮( ask for forgiveness not permission
)使用異常(只引發(fā)一次)而不是 if
分支(認(rèn)為) 例外情況)
添加回答
舉報(bào)
0/150
提交
取消