繁体   English   中英

将其他方法/函数/对象的文档字符串“移植”到类中的正确方法?

[英]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 因此,我想“端口”(这是正确的术语?)的文档字符串barFoo加入该行__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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM