2010-09-14 71 views

回答

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] 
相關問題