文档是非常重要的,它不仅可以向其他人传达一个函数/类/方法/模块的目标是什么,也可以向自己传达。
当你在6个月或12个月后回到你的代码时,你可能不记得你头脑中的所有知识,阅读你的代码并理解它应该做什么,将变得更加困难。
注释是一种方法。
# this is a comment
num = 1 #this is another comment
另一个方法是使用文档串。
文档串的效用在于它们遵循惯例,因此它们可以被自动处理。
这就是你如何为一个函数定义一个文档串。
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
def bark(self):
"""Let the dog bark"""
print('WOF!')
通过在文件的顶部放置一个文档串来记录一个模块,例如,假设这是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
def bark(self):
"""Let the dog bark"""
print('WOF!')
文档串可以跨越多行。
def increment(n):
"""Increment
a number
"""
return n + 1
Python 将处理这些文件,你可以使用help() 全局函数来获得一个类/方法/函数/模块的文档。
例如,调用help(increment) 会得到这个。
Help on function increment in module
__main__:
increment(n)
Increment
a number
有许多不同的标准来格式化文档,你可以选择遵守你最喜欢的一个。
我喜欢谷歌的标准:https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings
标准允许有工具来提取文档串,并为你的代码自动生成文档。