Python中的自定义文档字符串

时间:2018-10-10 01:10:48

标签: python docstring

如何在python中创建自定义文档字符串?您是说__nameofdocstring__还是要做其他事情?

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

1 个答案:

答案 0 :(得分:2)

文档字符串示例

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

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