我得到了一段这样的代码:
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似乎是在最外面的范围内搜索的。
发布于 2012-03-07 22:29:20
不,最好的替代方法是函数属性。
发布于 2012-03-07 22:41:24
为此,我使用了1元素列表:
def outer():
foo = [0]
def make_id():
r = foo[0]
foo[0] += 1
return r
return make_id
make_id = outer()
id1 = make_id()
id2 = make_id()
...这与使用nonlocal相同,但代价是语法稍显繁琐(使用foo[0]而不是foo)。
发布于 2012-03-07 22:34:27
不,将其作为make_id函数的参数。更好的做法是将您的id放在一个类中,并将make_id作为实例方法,并将该实例作为全局实例(如果需要)。
https://stackoverflow.com/questions/9603278
复制相似问题