如何在脚本中获取对象列表,以便可以在每个脚本上打印__doc__?

时间:2014-02-12 14:00:40

标签: python docstring

在我的脚本test.py中,我有很多函数和类,然后我有以下内容:

for i in dir():
    if i[0] != '_':
        print(type(i), i.__doc__)

但它不起作用,因为当使用dir()获取我的命名空间中的内容列表时,我得到一个字符串列表而不是对象。 如何在我的脚本中打印所有对象(包含docstrings)的文档字符串?

解决方案基于Ashwini Chaudhary的回答

我在加载模块后将它放在main()函数中:

# Print out all the documentation for all my functions and classes at once 
    for k, obj in sorted(globals().items()): #vars().items():
        if k[0] != '_' and hasattr(obj,'__doc__'):
#           if type(obj) != 'module' and type(obj) != 'str' and type(obj) != 'int':
                print(k, obj.__doc__)# == 'class': # or type(obj) == 'function'):
    sys.exit()

由于某些原因if type(obj) != 'module'不受尊重,所以我不能将其用作过滤器来获取我自己的函数。但现在就可以了。

2 个答案:

答案 0 :(得分:2)

您可以使用vars().items()

for k, obj in vars().items():
    if k[0] != '_':
       print(type(obj), obj.__doc__)
help()上的

vars

vars(...)
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.

答案 1 :(得分:1)

如果dir正在为您提供所需内容,则可以使用globals自行查找对象。

for i in dir():
    if i[0] != '_':
        item = globals()[i]
        print(type(item), item.__doc__)

如果您希望更好地控制所获得的内容,可以使用inspect.getmembers。为了获得对当前模块的引用,您需要sys中记录的{{1}}。

相关问题