Python 的 pydoc 帮助函数从哪里获取其内容?
我有很多可调用对象,它们都正确填写了 __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)
看起来更像是输出:
def myFunc():
"some doco text"
# do some stuff
pass
help(myFunc)
I have a lot of callable objects and they all have the __doc__
string correctly filled out, but running help on them produces the help for their class instead of help based on __doc__
.
I want to change it so that running help on them produces customized help that looks essentially like what I would get if they were actual functions instead of instances of a class that implements __call__
.
In code, I'd like to make the output of this:
class myCallable:
def __init__(self, doc):
self.__doc__ = doc
def __call__(self):
# do some stuff
pass
myFunc = myCallable("some doco text")
help(myFunc)
Look more like the output of this:
def myFunc():
"some doco text"
# do some stuff
pass
help(myFunc)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
help
函数(在pydoc
模块中实现)不准备查找每个实例的文档字符串。我快速浏览了该模块,看看是否有办法提供明确的帮助,但似乎没有。它使用inspect
模块来确定它是什么类型的东西,并且你的 myFunc 看起来不像一个函数,它看起来像一个实例。因此 pydoc 会打印有关实例类的帮助。如果与
__doc__
类似,您可以添加一个__help__
属性,那就太好了,但不支持这样做。我犹豫是否建议这样做,但最好的选择可能是定义一个新的
help
函数:然后在您的实例上放置一个
__help__
属性:The
help
function (implemented in thepydoc
module) isn't prepared to find per-instance docstrings. I took a quick look through the module to see if there was a way to provide explicit help, but there doesn't seem to be. It uses theinspect
module to determine what kind of thing it is, and your myFunc doesn't look like a function, it looks like an instance. So pydoc prints help about the instance's class instead.It'd be nice if similar to
__doc__
you could add a__help__
attribute, but there's no support for that.I hesitate to suggest it, but your best bet might be to define a new
help
function:and then put a
__help__
attribute on your instances:我不太清楚你的问题到底是什么。我的理解是,你有一个类和其中定义的函数,并且你想知道 Python 从哪里获取该函数的帮助文本。
Python 从该类/方法中提供的文档字符串中获取帮助文本。
如果您有一个类“A”和该类中的方法“f”,并且函数“f”中有文档字符串,那么以下终端转储应该有助于清除您的问题:
希望这有帮助
I'm not very clear about what your question is exactly. My understanding is that you have a class and a function defined in it and you want to know where Python gets the help text for that function from.
Python gets the help text from the doc strings provided in that class/method.
If you have a class "A" and a method "f" in that class and there are docstrings in the function "f", then the following terminal dump should help clear your question:
Hope this helps