How to Writing Docstring

在python中,如何写好docstring也是个值得学习的东西。

单行

示例:

1
"""This is a quick summary line used as a description of the object."""

多行

多行docstring包含如下几个部分:

  • 一行概要描述
  • 概要描述后跟一个空行
  • 更详细的描述
  • docstring后跟一个空行

示例:

1
2
3
4
5
6
7
8
9
"""This is the summary line

This is the further elaboration of the docstring. Within this section,
you can elaborate further on details as appropriate for the situation.
Notice that the summary and the elaboration is separated by a blank new
line.
"""

# Notice the blank line above. Code should continue on this line.

docstring的种类

  • Class Docstring
  • Package and Module Docstring
  • Scrip Docstring

Class Docstring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Animal:
"""
A class used to represent an Animal

...

Attributes
----------
says_str : str
a formatted string to print out what the animal says
name : str
the name of the animal
sound : str
the sound that the animal makes
num_legs : int
the number of legs the animal has (default 4)

Methods
-------
says(sound=None)
Prints the animals name and what sound it makes
"""

says_str = "A {name} says {sound}"

def __init__(self, name, sound, num_legs):
"""
Parameters
----------
name : str
The name of the animal
sound : str
The sound the animal makes
num_legs : int, optional
The number of legs the animal (default is 4)
"""

self.name = name
self.sound = sound
self.num_legs = num_legs

def says(self, sound=None):
"""Prints what the animals name is and what sound it makes.

If the argument `sound` isn't passed in, the default Animal
sound is used.

Parameters
----------
sound : str, optional
The sound the animal makes (default is None)

Raises
------
NotImplementedError
If no sound is set for the animal or passed in as a
parameter.
"""

if self.sound is None and sound is None:
raise NotImplementedError("Silent Animals are not supported!")

out_sound = self.sound if sound is None else sound
print(self.says_str.format(name=self.name, sound=out_sound))

应包含如下信息:

  • 简短描述类的目的和行为
  • 公共方法,配上一个简短描述
  • 类属性
  • 给子类的接口

参考文档

0%