[英]correct way to "porting" docstrings of other methods/functions/objects into a class?
这是我在做什么:
class Foo:
def __init__(self, **kwargs):
"""
docstring of Foo.
"""
self.sum = bar(**kwargs)
__init__.__doc__ += bar.__doc__
def bar(a, b):
"""
docstring of bar.
a: int
b: int
"""
print(a+b)
我想做的是: bar
定义了一些计算。 Foo
类使用bar
。 我想避免重复代码,即我想避免编写例如a: int
in Foo
。 因此,我想“端口”(这是正确的术语?)的文档字符串bar
为Foo
加入该行__init__.__doc__ += bar.__doc__
。
这是正确的方法吗? 我在黑客吗? 假设Foo
是 API 的一部分,而bar
是后台子程序。 向用户显示bar
的文档字符串的正确方法是什么?
您需要在Foo
之前定义bar
。 在您当前的配置中,在执行类体时,全局命名空间中不存在名称bar
。
您可能会考虑在文档之间添加换行符或某种分隔符:
__init__.__doc__ += '\n' + bar.__doc__
文档很少直接从文档字符串中读取。 更好的答案是使用sphinx 之类的工具以 HTML 或 PDF 等格式生成可用文档。 您可以链接到它,而不是将bar
的文档复制并粘贴到Foo.__init__
的文档中。 这样做的好处是您不需要重新排列全局命名空间中的对象。
流行的绘图库matplotlib是您确切用例的一个很好的例子。 它有很多函数,比如matplotlib.pyplot.subplots
,它通过剩余的参数( fig_kw
)传递给matplotlib.pyplot.figure
。 查看docstring的来源,我们看到:
**fig_kw All additional keyword arguments are passed to the `.pyplot.figure` call.
反引号在 sphinx 中生成一个链接。 您可以以类似的方式编写Foo.__init__
的文档字符串:
"""
docstring of Foo.
Parameters
----------
**kwargs
Arguments passed through to `bar`.
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.