Python的pydoc help函数从何处获取其内容?

2024-09-28 13:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多可调用的对象,它们都正确地填写了__doc__字符串,但是对它们运行帮助会生成其类的帮助,而不是基于__doc__的帮助。在

我想更改它,以便对它们运行帮助可以生成定制的帮助,基本上看起来像是如果它们是实际函数而不是实现__call__的类的实例。在

在代码中,我希望输出以下内容:

class myCallable:
    def __init__(self, doc):
        self.__doc__ = doc

    def __call__(self):
        # do some stuff
        pass

myFunc = myCallable("some doco text")
help(myFunc)

看起来更像是这样的输出:

^{pr2}$

Tags: 对象实例函数字符串代码selfdocinit
2条回答

help函数(在pydoc模块中实现)没有准备好查找每个实例的docstring。我快速浏览了一下这个模块,看看是否有一种方法可以提供明确的帮助,但似乎没有。它使用inspect模块来确定它是什么类型的东西,而myFunc看起来不像函数,而是一个实例。所以pydoc打印实例类的帮助。在

如果与__doc__类似,可以添加一个__help__属性,但不支持该属性。在

我不太愿意建议,但您最好还是定义一个新的help函数:

old_help = help
def help(thing):
    if hasattr(thing, '__help__'):
        print thing.__help__
    else:
        old_help(thing)

然后在实例上添加__help__属性:

^{pr2}$

我不太清楚你的问题到底是什么。我的理解是,您在其中定义了一个类和一个函数,并且您想知道Python从哪里获得该函数的帮助文本。在

Python从类/方法中提供的doc字符串获取帮助文本。在

如果您在该类中有一个类“a”和一个方法“f”,并且函数“f”中有docstring,那么下面的终端转储应该有助于澄清您的问题:

>>> class A:
        def __init__(self):
            self.c = 0   # some class variable
        def f(self, x):
            """this is the documentation/help text for the function "f" """
            return x+1

>>> help(A.f)
Help on method f in module __main__:

f(self, x) unbound __main__.A method
this is the documentation/help text for the function "f" 

>>> A.f.__doc__
'this is the documentation/help text for the function "f" '

希望这有帮助

相关问题 更多 >

    热门问题