在类和文档字符串中应该记录什么是一致的吗?

2024-05-19 07:57:25 发布

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

对于类和__init__docstrings中应该记录的内容,我没有找到任何最佳实践。有时我发现构造函数参数已经记录在类docstring中,有时在__init__docstring中描述。我更喜欢描述类docstring中的构造,因为这是在创建新实例时调用的。但是__init__方法docstring中应该记录什么呢?


编辑:

我知道google styleguidegoogle docstring style example,但都不回答我的问题。docstring样式的示例确实说明

The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.

但是如果我选择将__init__函数的docstring放入类级docstring,那么__init__docstring应该包含什么呢?


Tags: the实例方法编辑内容initstylegoogle
3条回答

我不知道在这一点上有任何共识。

但是,sphinx autodoc模块允许从docstring文档生成文档,因此它倾向于强制执行一致的docstring文档。

在您的例子中,我将记录classclassdocstring中的构造函数参数是什么:

class MyClass:
    """I am a class.
    I do funny stuff

    :type tags: dict
    :param tags: A dictionary of key-value pairs
    """

    def __init__(tags):
        self.tags = tags

类的实际用法是由类似SampleClass(args)的命令初始化的,没有用户会键入SampleClass.__init__(args),因此 从最终用户的角度来看,当他们感到困惑时,他们更可能键入

help(SampleClass)

而不是

help(SampleClass.__init__)

因此,我认为将所有文档放入SampleClass的docstring中是有意义的 在__init__的docstring中输入“请参阅help(SampleClass)获取更多信息”,以防有人(或某个程序)看到它。

我个人在可能的情况下尝试使用google styleguide

使用__init__创建新实例时,应记录初始化的成员变量。然后其他人知道当他们以后需要在他们的代码中访问他们时,他们会期望什么。

来自google styleguide的示例:

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

相关问题 更多 >

    热门问题