Python Docstrings

文档非常重要,不仅要与其他人交流功能/类/方法/模块的目标,而且也要与您自己交流。

当您从现在开始的6或12个月回到您的代码时,您可能会不记得自己掌握的所有知识,而阅读代码并理解应该做什么将变得更加困难。

注释是这样做的一种方法:

# this is a comment

num = 1 #this is another comment

另一种方法是使用文档字符串

docstrings的实用程序是它们遵循约定,因此可以自动进行处理。

这是您为函数定义文档字符串的方式:

def increment(n):
    """Increment a number"""
    return n + 1

这是您为类和方法定义文档字符串的方式:

class Dog:
    """A class representing a dog"""
    def __init__(self, name, age):
        """Initialize a new dog"""
        self.name = name
        self.age = age
<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">bark</span>(self):
    <span style="color:#e6db74">"""Let the dog bark"""</span>
    <span style="color:#66d9ef">print</span>(<span style="color:#e6db74">'WOF!'</span>)</code></pre></div>

Document a module by placing a docstring at the top of the file, for example supposing this is dog.py:

"""Dog module

This module does ... bla bla bla and provides the following classes:

- Dog
...
"""

class Dog: “”“A class representing a dog”"" def init(self, name, age): “”“Initialize a new dog”"" self.name = name self.age = age

<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">bark</span>(self):
    <span style="color:#e6db74">"""Let the dog bark"""</span>
    <span style="color:#66d9ef">print</span>(<span style="color:#e6db74">'WOF!'</span>)</code></pre></div>

Docstrings can span over multiple lines:

def increment(n):
    """Increment
    a number
    """
    return n + 1

Python will process those and you can use the help() global function to get the documentation for a class/method/function/module.

For example calling help(increment) will give you this:

Help on function increment in module
__main__:

increment(n) Increment a number

There are many different standards to format docstrings, and you can choose to adhere to your favorite one.

I like Google’s standard: https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings

Standard allows to have tools to extract docstrings and automatically generate documentation for your code.


More python tutorials: