python - 如何用更短和自定义的内容有选择地覆盖 python 帮助(MYclass)中的文本?

标签 python python-2.7 docstring

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

有什么方法可以覆盖使用help(MYclass)(或help(MYmethod))显示的内容,以便它只显示(在本例中)一个-行文档字符串?

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

enter image description here

因此,我转而向 help 寻求帮助,但是 help 对于所有这些额外的模板行帮助太大

然后我想到重新定义help:

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

但我认为这是邪恶的;比如重新定义数字 7,我希望 help(some builtin) 仍然正常工作,并且选择性劫持只发生在 MYclasses 上。

总是有

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

结果为十九行。我只想显示我的一行文档字符串。

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)

最佳答案

您可以对内置的 help 函数进行 monkeypatch 以显示类的 __doc__ 字符串并返回到原始的 help对象:

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.

关于python - 如何用更短和自定义的内容有选择地覆盖 python 帮助(MYclass)中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53995957/

相关文章:

python - 读取文件时出现语法错误

python 和狮身人面像 : bullet point list in multiline google style docstring

python - 这段 python 代码中的文档字符串有什么用?

python - 将文档字符串中的预期结果指定为十六进制?

python - Django-filter如何更改占位符以替换[无效名称]?

python - 即使index_col=None,Pandas read_excel有时也会创建索引

python - 转换字典键并搜索它们

python - 在 IPython 启动时自动加载模块

python - 如何在 VSCode 上用 Python 读取 SQLite 数据库?

Python 循环不工作 (xlwt)