在C#和Visual Studio中,可以注释你的函数,这样你就可以告诉使用你的类的人输入参数应该是什么,应该返回什么,等等。在python中有什么类似的东西吗?
发布于 2009-11-11 20:09:08
我认为您所指的是,C#对代码注释的格式有很强的文化约定,Visual Studio提供了将这些注释收集在一起的工具,并根据商定的标记对它们进行格式化,等等。Java也是类似的,它的Javadoc。
Python有一些类似这样的约定,但它们并不那么强大。PEP 257涵盖了最佳实践,像Sphinx这样的工具很好地将它们收集在一起来生成文档。
正如其他答案所解释的那样,文档字符串是模块、类或函数中的第一个字符串。从词法上讲,它们只是一个字符串(通常用三个引号引起来以支持多行文档),但它们被保留为实体的__doc__
属性,因此可供工具轻松自省。
发布于 2009-11-11 19:36:09
在Python中,您可以像这样使用docstrings:
def foo():
""" Here is the docstring """
基本上,您需要在函数、类或模块的第一行使用三重引号字符串,才能将其视为文档字符串。
注意:,实际上我,你不需要使用带三重引号的字符串,但这是惯例。任何公升字符串都可以,但最好遵循惯例,使用三重引号字符串。
发布于 2009-11-11 19:50:59
正如在其他答案中提到的,函数顶部的字符串用作文档,如下所示:
>>> 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
...
要查看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)
许多从代码生成HTML文档的工具使用第一行作为函数的摘要,而字符串的其余部分提供额外的详细信息。因此,第一行应该保持简短,以便与生成的文档中的函数清单很好地匹配。
https://stackoverflow.com/questions/1714633
复制相似问题