【问题标题】:Custom Docstrings in PythonPython 中的自定义文档字符串
【发布时间】:2018-10-10 01:10:47
【问题描述】:

如何在 python 中创建自定义文档字符串?你会直接说__nameofdocstring__ 还是你应该做其他事情?

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

【问题讨论】:

  • “自定义文档字符串”是什么意思?听起来您有特定的想法,但您还没有说清楚它是什么。
  • 您是要修改现有的第三方函数,还是针对您编写的函数?
  • 我不知道。这对我来说还没有意义。我不知道你从什么开始,你的目的地更不清楚
  • 我以为我开始明白你想要什么了,但最后一条评论让我迷失了方向。说明您拥有什么、您想要什么以及您希望如何使用它
  • (通过“解释”,我的意思是:编辑问题以通过示例明确说明该信息)

标签: python docstring


【解决方案1】:

文档字符串示例

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

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

【讨论】:

  • 这真的是函数的正确用法吗?
  • “文档字符串”,以“文档”命名。就这样。你可以记录你的函数在做什么。
  • 如果您的问题已解决,请考虑将答案标记为正确(无论是我的、您自己的还是其他人的),以便像您这样的未来助手小精灵真正可以安全地跳过该问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-06-06
  • 2013-09-11
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
相关资源
最近更新 更多