【发布时间】:2012-03-25 02:05:26
【问题描述】:
我得到了这样一段代码:
foo = None
def outer():
global foo
foo = 0
def make_id():
global foo
foo += 1
return foo
id1 = make_id() # id = 1
id2 = make_id() # id = 2
id3 = make_id() # ...
我觉得在最外层定义 foo 很难看,我宁愿只在 outer 函数中使用它。正如我正确理解的那样,在 Python3 中,这是由 nonlocal 完成的。对于我想要的东西,有没有更好的方法?我更愿意在outer 中声明和分配foo 并可能在inner 中声明global:
def outer():
foo = 0
def make_id():
global foo
foo += 1 # (A)
return foo
id1 = make_id() # id = 1
id2 = make_id() # id = 2
id3 = make_id() # ...
(A) 不起作用,foo 似乎在最外层范围内搜索。
【问题讨论】: