geekdoc-python-zh/docs/pythonland/39.md

4.4 KiB
Raw Permalink Blame History

Python Docstring:记录您的代码

原文:https://python.land/deep-dives/python-docstring

python docstring 允许您更正式地记录代码。我们首先来看看 docstring 到底是什么。接下来,我们将创建自己的文档字符串。最后,我将向您展示如何读取 docstrings。

目录

什么是 Python docstring

让我们从定义什么是 docstring 开始。这直接取自 PEP-0257 ,其中介绍了文档字符串:

Docstring

A docstring is a string that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

Python 注释和文档字符串之间有着明显的区别。Python 解释器完全忽略注释,而文档字符串是解释器看到的实际的字符串。因为我们没有指定字符串所以在运行代码时解释器认为它是无用的实际上被忽略了。因此简而言之docstring 的效果是一样的:它是记录代码的一段文本。

然而,注释和文档字符串之间仍然有本质的区别,因为 Python 实际上可以在请求时找到并显示文档字符串,因为它被赋予了__doc__特殊属性。您很快就会了解到,它可以作为一种正式记录代码的方式。

Thank you for reading my tutorials. I write these in my free time, and it requires a lot of time and effort. I use ads to keep writing these free articles, I hope you understand! Support me by disabling your adblocker on my website or, alternatively, buy me some coffee. It's much appreciated and allows me to keep working on this site!

如何创建 Python 文档字符串

如上所述,我们可以简单地插入一个字符串作为任何模块、函数、类或方法的第一条语句,它就成为 docstring。下面是一个如何使用文档字符串记录一个 Python 类及其函数的例子:

class MyDocumentedClass:
    """This class is well documented but doesn't do anything special."""

    def do_nothing(self):
        """This method doesn't do anything but feel free to call it anyway."""
        pass

如你所见,我用三重引号创建了这些字符串。这是有原因的:作为一个 docstring它们更容易被识别并且以后(如果需要的话)更容易将它们扩展成多行字符串。

如何读取文档字符串

docstring 在内部被分配给__doc__特殊属性。但是,通常情况下,您不会以这种方式访问它。相反,我们在 Python REPL 中调用help(MyDocumentedClass)来查看这些文档字符串的结果:

Help on class MyDocumentedClass in module __main__:

class MyDocumentedClass(builtins.object)
 |  This class is well documented but doesn't do anything special
 |
 |  Methods defined here:
 |
 |  do_nothing(self)
 |      This method doesn't do anything but feel free to call it anyway

下面是同一个班级的一个互动例子,你可以自己尝试一下:

https://crumb.sh/embed/3NduXvFKHzK

将 docstrings 应用于我们的类,并使用帮助功能打印它们

您可以使用 Python 中任何对象的帮助。我鼓励你试试这个。例如,输入help(print)从 print 函数获取 docstring或者输入help(str)查看 string 类及其所有有用的方法。你也可以要求一个类中的方法的文档,例如,使用help(str.title)你可以学习字符串对象上的title()方法做什么。

继续学习

  • PEP-0257 中提出并详细描述了文档字符串
  • Python 注释用于进一步记录和解释你的代码