看看下面的例子從一個全新的Python 3.4命令行啓動:
>>> len(globals())
6
>>> len(locals())
6
蝙蝠有6個全局變量和,因爲我們在全球範圍內目前是,有6個地方變數太多:
>>> a = 1
>>> b = 2
>>> c = 3
>>> len(globals())
9
>>> len(locals())
9
現在我們增加了3個變量,這兩個現在9.
>>> def foo():
... a = 1
... b = 2
... print(len(locals()))
... print(len(globals()))
...
現在我們已經添加了功能foo
(這是在全球範圍內定義,因此也被全局/當地人當在全球範圍內數):
>>> print(len(locals()))
10
>>> print(len(globals()))
10
最後,請注意函數中,只有在函數中的變量是本地人,而全局仍然包含在全球範圍內的一切:
>>> foo()
2
10
使用這個邏輯,你可以使用len(locals())
得到的函數中定義的變量/函數的數量和len(globals()) - 6
獲得全局中定義的所有變量/函數的列表 範圍。
編輯(請注意,所有的下面是一個新鮮的終端)
使用:
sum([not callable(globals()[i]) for i in globals()])
你可以得到的變量(不包括函數)的數量目前在全球範圍內。通過在你的代碼,然後每個呼叫的頂部添加globs = sum([not callable(globals()[i]) for i in globals()])
因此提出的
>>> a = 1
>>> b = 2
>>> c = 3
>>> sum([not callable(globals()[i]) for i in globals()]) - globs - 1
3
>>> def foo():
... a = 1
... b = 1
... print(len(locals()))
...
>>> foo()
2
>>> sum([not callable(globals()[i]) for i in globals()]) - globs - 1
3
這樣:通過指定這一個變量,你就可以得到當前定義的變量列表:
>>> globs = sum([not callable(globals()[i]) for i in globals()])
>>> sum([not callable(globals()[i]) for i in globals()]) - globs - 1 # -1 for globs
0
現在sum([not callable(globals()[i]) for i in globals()]) - globs - 1
將給出定義的變量數量(這是在全局範圍內,您可以使用locs = sum([not callable(locals()[i]) for i in locals()])
的類似方法在函數內執行相同的操作)。
編輯2
我不知道有這樣做你問的是什麼原生的方式,但是你有兩個選擇:
- 解析腳本(這是一個很大的功夫)
- 請您在每個函數調用結束遞增計數器:
>>> num_encountered_locals = 0
>>> def foo():
global num_encountered_locals
a = 1
b = 2
num_encountered_locals += len(locals())
>>> num_encountered_locals
0
>>> foo()
>>> num_encountered_locals
2
>>> foo()
>>> foo()
>>> foo()
>>> num_encountered_locals
8
(出於某種原因,所以我不得不把它放在手動<code>
和<pre>
標籤這最後大量的代碼將無法正常格式化)
做'LEN(當地人())'和'LEN(全局()) '完成你在找什麼? –
我不這麼認爲。我剛剛嘗試了一個簡單的測試腳本:a = 1,b = 2,c = 3,我希望len(locals())= 0和len(globals())= 3,但是我得到了11和11. – Astrophe