我得到了一段这样的代码:
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() # ...
Run Code Online (Sandbox Code Playgroud)
我发现foo在最外面的scop中定义它很难看,我宁愿只在outer函数中使用它.据我所知,在Python3中,这是通过nonlocal.对于我想拥有的东西,有更好的方法吗?我更愿意申报和分配foo,outer并可能在delcare global中inner:
def outer():
foo = 0
def make_id():
global foo
foo += 1 # (A)
return foo
id1 = make_id() # id = 1
id2 = make_id() …Run Code Online (Sandbox Code Playgroud) 我试图理解 Python 3 变量范围和nonlocal.
考虑以下函数(这只是一个示例):
def build_property(something):
def deco(func):
def getter(self):
return getattr(self, something)
def setter(self, value):
setattr(self, something, value)
return property(getter, setter)
return deco
Run Code Online (Sandbox Code Playgroud)
这在没有nonlocal. 但如果现在我想根据something我需要的非本地条件有条件地创建 getter 和 setter。
def build_property(something):
def deco(func):
nonlocal something # This is needed
if something.startswith('A'):
getter = None
else:
def getter(self):
return getattr(self, something)
if something.startswith('B'):
setter = None
else:
def setter(self, value):
setattr(self, something, value)
return property(getter, setter)
return deco
Run Code Online (Sandbox Code Playgroud)
为什么nonlocal在一种情况下需要,但在另一种情况下不需要?换句话说,为什么something如果在第一种情况下正确找到(没有nonlocal …
给定堆栈框架和变量名称,如何判断该变量是否为非局部变量?例:
import inspect
def is_nonlocal(frame, varname):
# How do I implement this?
return varname not in frame.f_locals # This does NOT work
def f():
x = 1
def g():
nonlocal x
x += 1
assert is_nonlocal(inspect.currentframe(), 'x')
g()
assert not is_nonlocal(inspect.currentframe(), 'x')
f()
Run Code Online (Sandbox Code Playgroud)