Python 中的自定义文档字符串

Custom Docstrings in Python

如何在 python 中创建自定义文档字符串?你会直接说 __nameofdocstring__ 还是你还应该做些什么?

是否可以为某个 .py 文件创建新的文档字符串?我想写__notes__ = "blah blah blah",但只是说那句话行不通。

文档字符串示例

让我们展示一个多行文档字符串的例子:

def my_function():
"""Do nothing, but document it.

No, really, it doesn't do anything.
"""
pass

让我们看看打印出来时的效果

print my_function.__doc__

Do nothing, but document it.

    No, really, it doesn't do anything.

文档字符串声明

以下 Python 文件显示了 python 中的文档字符串声明 源文件:

"""
Assuming this is file mymodule.py, then this string, being the
first statement in the file, will become the "mymodule" module's
docstring when the file is imported.
"""

class MyClass(object):
    """The class's docstring"""

    def my_method(self):
        """The method's docstring"""

def my_function():
    """The function's docstring"""

如何访问文档字符串

以下是显示如何访问文档字符串的交互式会话

>>> import mymodule
>>> help(mymodule)

假设这是文件 mymodule.py 那么这个字符串,是 导入文件时,该文件将成为 mymodule 模块文档字符串。

>>> help(mymodule.MyClass)
The class's docstring

>>> help(mymodule.MyClass.my_method)
The method's docstring

>>> help(mymodule.my_function)
The function's docstring