Python代码注释

dev*_*ium 2 python

在C#中,通过Visual Studio,可以对函数进行注释,这样你就可以告诉谁在使用你的类输入参数应该是什么,它应该返回什么,等等.在python中是否有任何类似的东西?

And*_*are 9

在Python中,您使用如下文档字符串:

def foo():
    """ Here is the docstring """
Run Code Online (Sandbox Code Playgroud)

基本上,您需要在函数,类或模块的第一行上使用三引号字符串作为docstring.

注:其实我不具备使用三引号的字符串但是这是惯例.任何升字符串都可以,但最好坚持使用约定并使用三重引号字符串.


Ned*_*der 7

我认为你所得到的是C#对于代码注释的格式化具有强烈的文化习惯,Visual Studio提供了一起收集这些注释的工具,根据商定的标记格式化它们,等等.Java与Javadoc类似.

Python有一些像这样的约定,但它们并不那么强大. PEP 257涵盖了最佳实践,像Sphinx这样的工具可以很好地将它们收集在一起以生成文档.

正如其他答案所解释的那样,docstrings是模块,类或函数中的第一个字符串.从词汇上讲,它们只是一个字符串(通常是三重引用以允许多行文档),但它们作为__doc__实体的属性保留,因此可以通过工具轻松进行内省.


Pär*_*der 5

正如其他答案中所提到的,函数最顶部的字符串用作文档,如下所示:

>>> def fact(n):
...     """Calculate the factorial of a number.
... 
...     Return the factorial for any non-negative integer.
...     It is the responsibility of the caller not to pass
...     non-integers or negative numbers.
... 
...     """
...     if n == 0:
...         return 1
...     else:
...         return fact(n-1) * n
...
Run Code Online (Sandbox Code Playgroud)

要在Python解释器中查看函数的文档,请使用help:

>>> help(fact)
Help on function fact in module __main__:

fact(n)
    Calculate the factorial of a number.

    Return the factorial for any non-negative integer.
    It is the responsibility of the caller not to pass
    non-integers or negative numbers.
(END) 
Run Code Online (Sandbox Code Playgroud)

许多从代码生成HTML文档的工具使用第一行作为函数的摘要,而字符串的其余部分提供了其他详细信息.因此,第一行应该保持简短,以便很好地适应生成的文档中的函数列表.