def foo():
a = 1
b = 2
dir() # prints [a, b]
bar(?)
der bar(foo_pointer):
print dir(foo_pointer) # should print [a,b]
我正在尝试使用
bar(sys.modules[__name__].main)
,但这不是 [a,b]
,而是 ['__call__','__class__' .. .]
没有 a
和 b
。
我实际上想保护该指针以备后用,所以我不能只传递 [a,b]
。
最佳答案
使用 sys._getframe()
function访问调用框架。框架对象有一个 f_locals
属性,让您可以访问该框架的局部变量:
import sys
def bar():
caller = sys._getframe(1)
print caller.f_locals
关于python获取调用函数的当前变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19707848/