簡體   English   中英

python程序中使用的變量列表

[英]List of variables used in python program

我們如何在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

輸出量

變量-f,j,i

您可以從以下函數獲取此信息:

>>> fact.func_code.co_varnames
('i', 'f', 'j')

請注意,只有構建了它們的字節碼后,才會生成這些變量名。

>>> def f():
        a = 1
        if 0:
            b = 2
>>> f.func_code.co_varnames
('a',)

請注意,由於setattr和其他一些動態編程技術(例如exec ),變量名的集合可能是無限的。 但是,您可以使用ast模塊執行簡單的靜態分析:

import ast

prog = ("\ndef fact(i):\n    f=2\n    for j in range(2,i+1):\n        f = f*i\n"+
       "        i = i - 1\n    print 'The factorial of ',j,' is ',f")
res = set()
for anode in ast.walk(ast.parse(prog)):
    if type(anode).__name__ == 'Assign':
        res.update(t.id for t in anode.targets if type(t).__name__ == 'Name')
    elif type(anode).__name__ == 'For':
        if type(anode.target).__name__ == 'Name':
            res.add(anode.target.id)
print('All assignments: ' + str(res))

在回答了類似的問題之前,我將在這里粘貼相關事件位:

要獲得在當前名稱空間中查找內容的幫助,請查看pprint庫內置目錄dir,內置 本地 變量和內置全局變量

請注意,在實際運行之前,函數不存在任何變量。 請參閱JBernardo的答案以獲取已編譯函數中的變量。 例如:

>>> def test():
...     i = 5
...
>>> locals()
{'argparse': <module 'argparse' from 'c:\python27\lib\argparse.pyc'>, '__builtins__': <module '
__builtin__' (built-in)>, '__package__': None, 'i': 5, 'test': <function test at 0x02C929F0>, '
__name__': '__main__', '__doc__': None}
>>> dir(test)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__',
 '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__',
 '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'fu
nc_dict', 'func_doc', 'func_globals', 'func_name']
>>>

查看測試函數在本地名稱空間中的位置。 我已經在上面調用了dir()來查看有趣的內容,並且未列出i變量。 將其與類聲明和對象創建進行比較:

>>> class test():
...     def __init__(self):
...          self.i = 5
...
>>> s = test()
>>> locals()
{'argparse': <module 'argparse' from 'c:\python27\lib\argparse.pyc'>, '__builtins__': <module '
__builtin__' (built-in)>, '__package__': None, 'i': 5, 's': <__main__.test instance at 0x02CE45
08>, 'test': <class __main__.test at 0x02C86F48>, '__name__': '__main__', '__doc__': None}
>>> dir(s)
['__doc__', '__init__', '__module__', 'i']
>>>

最后,請注意,如果這些項是變量,常量,函數,甚至是在類內部聲明的類,怎么也不會說! 使用風險自負。

globals()將返回所有全局變量的字典。

locals()將返回所有局部變量的字典,例如,其調用范圍內的所有變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM