文档字符串应该放在装饰器之前还是之后?
比较以下内容。
示例 1:装饰器之前的文档字符串。
@app.route("/")
"""
summary
"""
def hello() -> str:
return "Hello World"
对比示例 2:装饰器后的文档字符串:
"""
summary
"""
@app.route("/")
def hello() -> str:
return "Hello World"
Compare the following.
Example 1: docstring before decorator.
@app.route("/")
"""
summary
"""
def hello() -> str:
return "Hello World"
versus example 2: docstring after decorator:
"""
summary
"""
@app.route("/")
def hello() -> str:
return "Hello World"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文档字符串应该放在哪里?
文档字符串应该放在函数内部,函数头之后的第一件事:
规范本身(PEP 257)明确表示:
为什么?
这很重要,因为文档字符串不仅仅是一种约定。
如果将它们放在正确的位置,您可以使用 < 查看函数文档code>help() function (甚至可能是其他工具):
发生这种情况是因为,如果字符串文字是函数声明中的第一个内容,解释器会将其设置为
__doc__
函数的属性:help()
基本上只是以良好的格式显示__doc__
属性的值。Where should the docstring go?
The docstring should go inside the function, the first thing after the function header:
The specification itself (PEP 257) makes it explicit:
Why?
It is important because docstrings are not just a convention.
If you put them in the right place, you can see the function documentation with the
help()
function (and maybe even other tools):This happens because, if a string literal is the first thing in the function declaration, the interpreter will set it to the
__doc__
attribute of the function:help()
basically just displays, nicely formatted, the value of the__doc__
attribute.两者都不应该放在函数标题下,如下所示:
PEP 257更详细地讨论文档字符串的约定。它指出这些文档字符串被设置为给定函数或类的 __doc__ 属性(如上面链接的 PEP 中所述)。
这些文档字符串在调用
help()
时出现,如下所示:您描述的其他展示位置未设置
__doc__
属性,因此与help()
的行为不同。Neither, they should go under the function header, like so:
PEP 257 discusses the convention for docstrings in more detail. It states that these docstrings are set to the
__doc__
attribute of a given function or class (as described in the PEP linked above).These docstrings appear when
help()
is invoked, like as follows:The other placements you've described do not set the
__doc__
attribute, and thus do not have the same behavior withhelp()
.