Python code comments
In C# and through Visual Studio, it is possible to comment your functions, so you can tell whoever is using your class what the input arguments shou开发者_Go百科ld be, what it is supposed to return, etc. Is there anything remotely similar in python?
In Python you use docstrings like this:
def foo():
""" Here is the docstring """
Basically you need to have a triple quoted string be on the first line of a function, class, or module to be considered a docstring.
Note: Actually I you don't have to use a triple quoted string but that is the convention. Any liter string will do but it is best to stick with convention and use the triple quoted string.
I think what you are getting at is that C# has a strong cultural convention for the formatting of code comments, and Visual Studio provides tools that collect those comments together, format them according to agreed markup, and so on. Java is similar, with its Javadoc.
Python has some conventions like this, but they are not as strong. PEP 257 covers the best practices, and tools like Sphinx do a good job of collecting them together to produce documentation.
As other answers have explained, docstrings are the first string in a module, class, or function. Lexically, they are simply a string (usually triple-quoted to allow multi-line documentation), but they are retained as the __doc__
attribute of the entity, and therefore available for easy introspection by tools.
As mentioned in other answers, a string at the very top of the function serves as documentation, like this:
>>> 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
...
To see the documentation for a function in the Python interpreter, use 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)
Many tools that generate HTML documentation from code use the first line as a summary of the function, while the rest of the string provides additional details. Thus, the first line should be kept short to fit nicely in function listings in generated documentation.
Just put a string anywhere you like. If there is a string as the first thing in a method, Python will put it in the special field __doc__
:
def f():
"""This is the documentation"""
pass
"""But you can have as many comments as you like."""
print f.__doc__
精彩评论