简体   繁体   English

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

[英]How do you get a list of objects in a script so that you can print __doc__ on each of them?

In my script test.py I have a lot of functions and classes and then I have the following: 在我的脚本test.py我有很多函数和类,然后有以下内容:

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

But it doesnt work because when using dir() to get a list of what is in my namespace, I get a list of strings and not objects. 但这是行不通的,因为使用dir()获取名称空间中内容的列表时,我得到的是字符串列表,而不是对象列表。 How can I print the docstrings of all the objects (that have docstrings) in my script? 如何在脚本中打印所有对象(具有文档字符串)的文档字符串?

Solution based on Ashwini Chaudhary's answer 基于Ashwini Chaudhary答案的解决方案

I put this in my main() function after the module has been loaded: 加载模块后,将其放入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()

For some reason if type(obj) != 'module' is not respected so I couldnt use that as a filter to get only my own functions. 由于某种原因, if type(obj) != 'module'不尊重if type(obj) != 'module'那么我就不能将其用作仅获取自己函数的过滤器。 But that is OK for now. 但这暂时还可以。

You can use vars().items() : 您可以使用vars().items()

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

help() on vars : vars上的help()

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

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

if dir is giving you the stuff you want, you can use globals to look up the objects themselves. 如果dir正在为您提供所需的东西,则可以使用globals来查找对象本身。

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

If you want more fine control over what you get, you can use inspect.getmembers . 如果要更好地控制所获得的内容,可以使用inspect.getmembers In order to get a reference to the current module, you need sys as documented in this answer . 为了获得对当前模块的引用,您需要sys本答案中所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM