And*_*den 7 python scope local-variables
假设我有一个函数层次结构,我希望能够访问(不更改!)父项范围.这是一个说明性的例子.
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()
Run Code Online (Sandbox Code Playgroud)
我可以f
从内部访问范围g
吗?
一般来说,你不能在Python中.如果您的Python实现支持堆栈帧(CPython),您可以使用inspect
模块检查调用函数的框架并提取局部变量,但我怀疑这是您想要解决的问题的最佳解决方案(无论可能是什么).如果你认为你需要这个,你的设计中可能存在一些缺陷.
请注意,使用inspect
将使您能够进入调用堆栈,而不是在词法范围的堆栈中.如果你g
从中返回f()
,那么范围f
将会消失,所以根本不可能访问它,因为它甚至不存在.