如何在下层函数中找到中层函数中的变量
如题, 不能使用参数传递, 不能使用 global !
请问在执行被呼叫函数 debug 中, 呼叫函数中当时, 除了 global 的变量以外, local 的变量如何取得 ?
目的: 某些情况不适合把所有的变量宣告, 比如 debug 函数, 当f2 呼叫debug 时, debug 要处理在f2 能看到的所有的变量, 它可能是是local, 也可能是global. 使用global或nonlocal 宣称所有的变量, 或者把debug 只定义在f2 都是不合适的, 因为目的中, debug 是个通用函数, 不只使用在f2.
目的不是只针对 debug.
def debug():
"""
Common function used anywhere in Python
It will access all variables where this function called.
all_variables_dictionary
for variable in all_variable_dictionary:
print(f"{variable} = {all_variable_dictionary[variable]}')
"""
print('a10 in globals():', 'a10' in globals())
print('a10 in locals():', 'a10' in locals())
print(a10)
def f2():
a10 = 5
debug()
f2()
a10 in globals(): False
a10 in locals(): False
Traceback (most recent call last):
File "<string>", line 178, in run_nodebug
File "D:\module1.py", line 16, in <module>
f2()
File "D:\module1.py", line 14, in f2
debug()
File "D:\module1.py", line 10, in debug
print(a10)
NameError: name 'a10' is not defined
推荐文章: