Skip to main content
 首页 » 编程设计

python之Python 是否有返回模块中所有属性的方法

2025年05月04日10lhb25

我已经在 Google 上搜索过了,但没有找到。

请您参考如下方法:

除了已经提到的 dir 内置函数之外,还有 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]