gpt4 book ai didi

python - 对类和 __init__ 文档字符串中应记录的内容是否达成共识?

转载 作者:IT老高 更新时间:2023-10-28 20:41:57 33 4
gpt4 key购买 nike

我没有找到任何关于应该在类和 __init__ 文档字符串中记录什么的最佳实践。有时我发现构造函数参数已经记录在类文档字符串中,有时在 __init__ 文档字符串中进行了描述。我更喜欢在类文档字符串中描述构造,因为这是您在创建新实例时所调用的。但是应该在 __init__ 方法文档字符串中记录什么?


编辑:

我知道 google styleguidegoogle docstring style example ,但两者都没有回答我的问题。文档字符串样式示例确实说

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

但是如果我选择将__init__函数的docstring放到class级别的docstring中,__init__ docstring应该包含什么?

最佳答案

有一个官方答案,在 PEP 257 (文档字符串 PEP),可以说是权威的:

The class constructor should be documented in the docstring for its __init__ method.

这很合乎逻辑,因为这是函数和方法的常用过程,__init__() 也不异常(exception)。

因此,这会将代码及其文档放在同一个位置,这有助于维护。

最后,向用户显示文档的工具(如 Jupyter,或内置的 Python shell 命令 help())更有可能正确显示代码的文档。在实践中,当您在 class 上寻求帮助时,它们确实会自动显示 __init__() 文档字符串,因此这是另一个值得关注的理由将初始化文档放入 __init__() 的官方约定。

关于python - 对类和 __init__ 文档字符串中应记录的内容是否达成共识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019744/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com