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: