【问题标题】:Printing help docstring of all the functions in the string module: Python打印字符串模块中所有函数的帮助文档字符串:Python
【发布时间】:2019-01-01 13:58:13
【问题描述】:

我正在尝试在strings module 中打印所有functions 及其help docstrings,但没有得到预期的结果。以下是我尝试过的事情:

r = 'A random string'

1.  [help(fn) for fn in r.__dir__() if not fn.startswith('__')]
2.  [help(r.fn) for fn in r.__dir__() if not fn.startswith('__')]
3.  [fn.__doc__ for fn in r.__dir__() if not fn.startswith('__')]
4.  [r.fn.__doc__ for fn in r.__dir__() if not fn.startswith('__')]

还有更多。其中一些抛出错误,指出r 没有名为'fn' 的属性。其他人只是打印'str' 函数的帮助文档。有什么方法可以动态打印所有功能吗?

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    在python2中:

    for i in dir(r):
        if not i.startswith('__'):
            print getattr(r, i).__doc__
    

    在python3中:

    for i in dir(r):
        if not i.startswith('__'):
            print(getattr(r, i).__doc__)
    

    (基本一样,只改print函数)。您需要获取带有getattr 的方法对象才能显示其__doc__ 属性。

    【讨论】:

      【解决方案2】:

      要打印文档字符串,请使用 func.__doc__。

      r = 'A random string'
      
      for fn in r.__dir__():
        if not fn.startswith("__"):
          print ("Function:",fn)
          print (fn.__doc__)
          print()
      

      【讨论】:

      • 您是否尝试过运行您的代码。您的第一个打印语句中有错误。应该是print("Function: %s" %fn)。此外,此代码仅多次打印str 函数的文档。请再次检查并恢复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2021-11-06
      相关资源
      最近更新 更多