Python 文档字符串 vs 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19074745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:45:18  来源:igfitidea点击:

Docstrings vs Comments

pythoncommentsdocstring

提问by Jeremy

I'm a bit confused over the difference between docstrings and comments in python.

我对 python 中的文档字符串和注释之间的区别有点困惑。

In my class my teacher introduced something known as a 'design recipe', a set of steps that will supposedly help us students plot and organize our coding better in Python. From what I understand, the below is an example of the steps we follow - this so call design recipe (the stuff in the quotations):

在我的课堂上,我的老师介绍了一种称为“设计配方”的东西,这是一组据说可以帮助我们学生更好地用 Python 绘制和组织我们的编码的步骤。据我了解,以下是我们遵循的步骤的一个示例——这就是所谓的设计秘诀(引用中的内容):

def term_work_mark(a0_mark, a1_mark, a2_mark, ex_mark, midterm_mark):

    ''' (float, float, float, float, float) -> float

    Takes your marks on a0_mark, a1_mark, a2_mark, ex_mark and midterm_mark, 
    calculates their respective weight contributions and sums these 
    contributions to deliver your overall term mark out of a maximum of 55 (This
    is because the exam mark is not taken account of in this function)

    >>>term_work_mark(5, 5, 5, 5, 5)
    11.8
    >>>term_work_mark(0, 0, 0, 0, 0)
    0.0
    '''

    a0_component = contribution(a0_mark, a0_max_mark, a0_weight)
    a1_component = contribution(a1_mark, a1_max_mark, a1_weight)
    a2_component = contribution(a2_mark, a2_max_mark, a2_weight)
    ex_component = contribution(ex_mark, exercises_max_mark,exercises_weight)
    mid_component = contribution(midterm_mark, midterm_max_mark, midterm_weight)
    return (a0_component + a1_component + a2_component + ex_component + 
            mid_component)

As far as I understand this is basically a docstring, and in our version of a docstring it must include three things: a description, examples of what your function should do if you enter it in the python shell, and a 'type contract', a section that shows you what types you enter and what types the function will return.

据我所知,这基本上是一个文档字符串,在我们的文档字符串版本中,它必须包括三件事:描述,如果您在 python shell 中输入函数应该做什么的示例,以及“类型合同”,一个部分,显示您输入的类型以及函数将返回的类型。

Now this is all good and done, but our assignments require us to also have comments which explain the nature of our functions, using the token '#' symbol.

现在这一切都很好并且完成了,但是我们的作业还要求我们使用标记“#”符号来解释我们函数的性质的注释。

So, my question is, haven't I already explained what my function will do in the description section of the docstring? What's the point of adding comments if I'll essentially be telling the reader the exact same thing?

所以,我的问题是,我不是已经在文档字符串的描述部分解释了我的函数将做什么吗?如果我基本上要告诉读者完全相同的事情,那么添加评论有什么意义呢?

回答by Reza Shayestehpour

First of all, for formatting your posts you can use the help options above the text area you type your post.

首先,为了格式化您的帖子,您可以使用您键入帖子的文本区域上方的帮助选项。

And about comments and doc strings, the doc string is there to explain the overall use and basic information of the methods. On the other hand comments are meant to give specific information on blocks or lines, #TODO is used to remind you what you want to do in future, definition of variables and so on. By the way, in IDLE the doc string is shown as a tool tip when you hover over the method's name.

关于注释和文档字符串,文档字符串用于解释方法的整体使用和基本信息。另一方面,注释旨在提供有关块或行的特定信息,#TODO 用于提醒您将来要做什么、变量定义等。顺便说一下,在 IDLE 中,当您将鼠标悬停在方法名称上时,文档字符串会显示为工具提示。

回答by thefourtheye

Quoting from this page http://www.pythonforbeginners.com/basics/python-docstrings/

引用此页面http://www.pythonforbeginners.com/basics/python-docstrings/

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.

An object's docsting is defined by including a string constant as the first statement in the object's definition.

It's specified in source code that is used, like a comment, to document a specific segment of code.

Unlike conventional source code comments the docstring should describe what the function does, not how.

All functions should have a docstring

This allows the program to inspect these comments at run time, for instance as an interactive help system, or as metadata.

Docstrings can be accessed by the __doc__attribute on objects.

Python 文档字符串(或文档字符串)提供了一种将文档与 Python 模块、函数、类和方法相关联的便捷方式。

对象的 docsting 是通过在对象定义中包含一个字符串常量作为第一条语句来定义的。

它在源代码中指定,就像注释一样,用于记录特定的代码段。

与传统的源代码注释不同,文档字符串应该描述函数的作用,而不是如何。

所有函数都应该有一个文档字符串

这允许程序在运行时检查这些注释,例如作为交互式帮助系统或元数据。

可以通过对象上的__ doc__属性访问文档字符串。

  1. Docstrings can be accessed through a program (__doc__) where as inline comments cannot be accessed.
  2. Interactive help systems like in bpython and IPython can use docstrings to display the docsting during the development. So that you dont have to visit the program everytime.
  1. 可以通过程序 ( __doc__)访问文档字符串,而无法访问内联注释。
  2. 像 bpython 和 IPython 这样的交互式帮助系统可以在开发过程中使用 docstrings 来显示 docsting。这样您就不必每次都访问该程序。

回答by dejester

It appears your teacher is a fan of How to Design Programs ;)

看来你的老师是如何设计程序的粉丝;)

I'd tackle this as writing for two different audiences who won't always overlap.

我会将此作为为两个不同的观众写作来解决,他们不会总是重叠。

First there are the docstrings; these are for people who are going to be using your code without needing or wanting to know how it works. Docstrings can be turned into actual documentation. Consider the official Python documentation - What's available in each library and how to use it, no implementation details (Unless they directly relate to use)

首先是文档字符串;这些适用于将要使用您的代码而不需要或不想知道它是如何工作的人。文档字符串可以变成实际的文档。考虑官方 Python 文档 - 每个库中有什么可用以及如何使用它,没有实现细节(除非它们与使用直接相关)

Secondly there are in-code comments; these are to explain what is going on to people (generally you!) who want to extend the code. These will not normally be turned into documentation as they are really about the code itself rather than usage. Now there are about as many opinions on what makes for good comments (or lack thereof) as there are programmers. My personal rules of thumb for adding comments are to explain:

其次是代码内注释;这些是为了向想要扩展代码的人(通常是你!)解释发生了什么。这些通常不会变成文档,因为它们实际上是关于代码本身而不是用法。现在,关于什么是好的评论(或缺乏评论)的意见与程序员一样多。我个人添加评论的经验法则是解释:

  • Parts of the code that are necessarily complex. (Optimisation comes to mind)
  • Workarounds for code you don't have control over, that may otherwise appear illogical
  • I'll admit to TODOs as well, though I try to keep that to a minimum
  • Where I've made a choice of a simpler algorithm where a better performing (but more complex) option can go if performance in that section later becomes critical
  • 代码中必须复杂的部分。(想到优化)
  • 您无法控制的代码的解决方法,否则可能会显得不合逻辑
  • 我也会承认 TODO,尽管我尽量将其保持在最低限度
  • 我选择了一个更简单的算法,如果该部分的性能稍后变得至关重要,则可以选择性能更好(但更复杂)的选项

Since you're coding in an academic setting, and it sounds like your lecturer is going for verbose, I'd say just roll with it. Use code comments to explain how you are doing what you say you are doing in the design recipe.

由于您是在学术环境中编码,而且听起来您的讲师想要冗长,我会说只是顺其自然。使用代码注释来解释你是如何做你在设计秘诀中所说的。

回答by ivanleoncz

I believe that it's worth to mention what PEP8 says, I mean, the pure concept.

我相信值得一提的是 PEP8 所说的,我的意思是,纯粹的概念。

Docstrings

文档字符串

Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.

Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.

PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, e.g.:

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""

For one liner docstrings, please keep the closing """ on the same line.

编写好的文档字符串(又名“文档字符串”)的约定在 PEP 257 中永存。

为所有公共模块、函数、类和方法编写文档字符串。非公共方法不需要文档字符串,但您应该有一个注释来描述该方法的作用。此注释应出现在 def 行之后。

PEP 257 描述了良好的文档字符串约定。请注意,最重要的是,结束多行文档字符串的 """ 应该单独在一行上,例如:

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""

对于单行文档字符串,请将结尾的“””保留在同一行上。

Comments

注释

Block comments

阻止评论

Generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

Paragraphs inside a block comment are separated by a line containing a single #.

通常适用于它们后面的一些(或全部)代码,并且缩进到与该代码相同的级别。块注释的每一行都以 # 和一个空格开头(除非它是注释内的缩进文本)。

块注释内的段落由包含单个 # 的行分隔。

Inline Comments

内嵌注释

Use inline comments sparingly.

An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Inline comments are unnecessary and in fact distracting if they state the obvious.

Don't do this:

x = x + 1 # Increment x

But sometimes, this is useful:

x = x + 1 # Compensate for border

谨慎使用内联注释。

内联注释是与语句在同一行的注释。内联注释应与语句之间至少用两个空格隔开。它们应该以 # 和一个空格开头。

内联注释是不必要的,如果它们陈述显而易见的内容,实际上会分散注意力。

不要这样做:

x = x + 1 # 增加 x

但有时,这很有用:

x = x + 1 # 补偿边框

Reference

参考