代码之家  ›  专栏  ›  技术社区  ›  uhoh Jacob

如何有选择地用一些较短和定制的内容覆盖来自Python帮助(MyClass)的文本?

  •  4
  • uhoh Jacob  · 技术社区  · 7 年前

    我正在学习编写用户友好的类和方法,我想让用户知道如何从终端使用它们。巨蟒标准 help(MYclass) 返回我不想要的18行,这是一个小窗口的半屏幕,而那些只学习python的人将失去与前一行从顶部消失的连续性。

    有什么方法可以替代使用 帮助(MYclass) (或) help(MYmethod) )显示以便它只显示(在本例中)一行文档字符串?

    虽然一些IDE在气泡中显示docstring,但是终端不合作。( Do the triple-quoted (docstring) messages in Python appear while typing in IDEs other than IDLE? ):

    enter image description here

    因此,我转向 help 寻求帮助,但 帮助 过分帮助 所有这些额外的模板行。

    然后我想重新定义帮助:

    def hhelp(x):
        return x.__doc__
    help = hhelp
    

    但我认为这是邪恶的,就像重新定义数字7,我想 help(some builtin) 仍然正常工作,选择性劫持只发生在 MYclass 锿。

    总有

    def doc(x):
        return x.__doc__
    

    如果我找不到有选择劫持的东西 help() .


    class A(object):
        """instantiate a = A(x), then use a.sqr() to get x**2"""
        def __init__(self, x):
                self.x = x
        def sqr(self):
                return x**2
    

    结果是19行。我只想让我的一行文档串显示出来。

    Help on class A in module __main__:
    
    class A(__builtin__.object)
     |  instantiate a = A(x), then use a.sqr() to get x**2
     |  
     |  Methods defined here:
     |  
     |  __init__(self, x)
     |  
     |  sqr(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   a_guest    7 年前

    你可以修补内置的 help 函数来显示 __doc__ 类的字符串并返回到原始字符串 帮助 对于其他对象:

    import inspect
    import pydoc
    
    class Helper(object):
        def __init__(self):
            self.help = __builtins__.help
    
        def __call__(self, obj):
            if inspect.isclass(obj):
                return pydoc.pager(obj.__doc__)
            else:
                return self.help(obj)
    
    __builtins__.help = Helper()
    

    产生以下输出:

    class Foo:
        """This is the docstring."""
    
        def foo(self):
            return None
    
    help(Foo)
    
    # Output:
    # This is the docstring.
    
        2
  •  1
  •   a_guest    7 年前

    AS help(help) 表示它依赖于 pydoc ,具体地说 pydoc.help .

    |定义内置的“帮助”。
    |这是一个围绕pydoc.help的包装(有一个扭曲)。

    检查我们发现它依赖的源代码 TextDoc.docclass 为类生成帮助文本。所以我们可以使用monkeypatch方法来生成我们自己的帮助文本:

    import pydoc
    
    def docclass(self, object, *args, **kwargs):
        return pydoc.getdoc(object)
    
    pydoc.TextDoc.docclass = docclass
    

    现在我们只会得到 __doc__ 帮助文本中的字符串:

    class Foo:
        """This is the docstring."""
    
        def foo(self):
            return None
    
    help(Foo)
    
    # Output:
    # Help on class Foo in module __main__:
    # 
    # This is the docstring.
    

    1。语法特定于python 2.7,因为op使用了相应的标记。尽管它似乎也可以与其他版本的Python一起使用。

    推荐文章