假设我有一层层的函数,我想要能够访问 (但不改变!) 父级作用域。以下是一个说明性的例子。
def f():
a = 2
b = 1
def g():
b = 2
c = 1
print globals() #contains a=1 and d=4
print locals() #contains b=2 and c=1, but no a
print dict(globals(), **locals()) #contains a=1, d=4 (from the globals), b=2 and c=1 (from g)
# I want a=2 and b=1 (from f), d=4 (from globals) and no c
g()
a = 1
d = 4
f()
我可以从 g
中访问 f
的作用域吗?
f()
的本地变量也包括函数g
。 - Sven Marnach