我已經在Google上搜索它,但是我沒有運氣。Python是否有一個方法返回模塊中的所有屬性?
1
A
回答
4
import module
dir(module)
0
您正在尋找dir
:
import os
dir(os)
??dir
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
0
因爲它已被正確地指出的那樣,dir
函數會返回一個列表,在一個給定對象的所有可用的方法。
如果您從命令提示符調用dir()
,它將使用啓動時可用的方法進行響應。如果您致電:
import module
print dir(module)
將打印在模塊module
所有可用的方法列表。你只關心公共方法(那些你應該是使用)次數最多的 - 按照慣例,Python的私有方法和變量開始__
,所以我做的是以下幾點:
import module
for method in dir(module):
if not method.startswith('_'):
print method
那這樣,你只打印公共方法(可以肯定的 - 在_
僅僅是一個約定,許多模塊的作者,可能無法按照約定)
dir
內置
7
,有inspect
模塊其中有一個非常好的getmembers
方法。與pprint.pprint
結合你有一個強大的組合
from pprint import pprint
from inspect import getmembers
import linecache
pprint(getmembers(linecache))
一些樣本輸出:
('__file__', '/usr/lib/python2.6/linecache.pyc'),
('__name__', 'linecache'),
('__package__', None),
('cache', {}),
('checkcache', <function checkcache at 0xb77a7294>),
('clearcache', <function clearcache at 0xb77a7224>),
('getline', <function getline at 0xb77a71ec>),
('getlines', <function getlines at 0xb77a725c>),
('os', <module 'os' from '/usr/lib/python2.6/os.pyc'>),
('sys', <module 'sys' (built-in)>),
('updatecache', <function updatecache at 0xb77a72cc>)
注意,與dir
你能看到的是,成員的實際值。您可以對getmembers
應用類似於您可以應用到dir
的篩選器,他們可以更強大。例如,
def get_with_attribute(mod, attribute, public=True):
items = getmembers(mod)
if public:
items = filter(lambda item: item[0].startswith('_'), items)
return [attr for attr, value in items if hasattr(value, attribute]
0
dir
是你所需要的:)
相關問題
- 1. 是否有一個ruby方法只返回一個塊的值?
- 2. 屬性是否有方法?
- 3. 如何返回單個屬性而不是所有模型
- 4. Python是否將模塊路徑中的所有模塊導入?
- 5. 使用Yii findAll返回一個模型W /所有屬性
- 6. 子類是否具有父類的所有屬性和方法?
- 7. 是否有可能結束一個像返回類似的Python模塊導入?
- 8. 在Python中導入模塊的所有方法是什麼?
- 9. 是否有可能創建一個模塊或父類,使Ruby中的所有方法類方法?
- 10. 是否有一個從python csv模塊構建的方法來枚舉特定列的所有可能的值?
- 11. Python請求:Response.text屬性返回一個不是值的模板
- 12. 如何返回所有模塊的JSON?
- 13. 具有隻讀屬性的模擬方法返回值
- 14. 是否有一個屬性忽略了設計時的方法?
- 15. 所有Java屬性的方法是否完全同步?
- 16. 如何模擬一個模塊,但不是其中的所有方法?
- 17. 是否所有方法返回的東西
- 18. 在Angular.js中,是否有限制服務對一個模塊或模塊的「類」可見性的方法?
- 19. module_invoke_all不返回所有模塊
- 20. Python字典的keys()方法是否返回有序列表
- 21. GetLocalValueEnumerator()不返回所有屬性
- 22. GetDirectoryEntry不返回所有屬性
- 23. RetrieveMultiple不返回所有屬性
- 24. 此方法是否返回一個url?
- 25. 是否有可能從Java中的方法返回多個值?
- 26. python模塊'pandas'沒有屬性'繪圖'
- 27. 在返回一個基元double的方法中返回int是否會有性能損失?
- 28. Python:又一個AttributeError:'模塊'對象沒有任何屬性
- 29. 是否有一種測試Python中兩個對象的屬性是否等價的通用方法?
- 30. Python sklearn中是否有用於Non_Linear Logistic迴歸的模塊?