python程序中使用的变量列表

Rah*_*pta 3 python variables

我们怎样才能在python程序中找到所有变量?例如. 输入

def fact(i):
    f=2
    for j in range(2,i+1):
        f = f * i
        i = i - 1
    print 'The factorial of ',j,' is ',f
Run Code Online (Sandbox Code Playgroud)

产量

变量 - f,j,i

JBe*_*rdo 8

您可以从函数中获取此信息:

>>> fact.func_code.co_varnames
('i', 'f', 'j')
Run Code Online (Sandbox Code Playgroud)

请注意,只有在构建了它们的字节码时,才会生成这些变量名称.

>>> def f():
        a = 1
        if 0:
            b = 2
>>> f.func_code.co_varnames
('a',)
Run Code Online (Sandbox Code Playgroud)