在C#中,通过Visual Studio,可以对函数进行注释,这样你就可以告诉谁在使用你的类输入参数应该是什么,它应该返回什么,等等.在python中是否有任何类似的东西?
在Python中,您使用如下文档字符串:
def foo():
""" Here is the docstring """
Run Code Online (Sandbox Code Playgroud)
基本上,您需要在函数,类或模块的第一行上使用三引号字符串作为docstring.
注:其实我不具备使用三引号的字符串但是这是惯例.任何升字符串都可以,但最好坚持使用约定并使用三重引号字符串.
正如其他答案中所提到的,函数最顶部的字符串用作文档,如下所示:
>>> 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文档的工具使用第一行作为函数的摘要,而字符串的其余部分提供了其他详细信息.因此,第一行应该保持简短,以便很好地适应生成的文档中的函数列表.