2019/05/19 更新
没想到这个答案被人翻了出来,因为原答案是刚刚开始学编程的时候写的,质量不高,没有答清楚,现在尝试改进一下
一般来说,文档字符串(docstring)偏向于对特定模组(module)、函数(function)、类(class)和方法(method)的一个总体介绍,更注重于告诉其他程序员应该怎么使用这些模组/函数/类/方法;而注释(comment)则注重于记录代码实现的细节
来看个例子,Python官方的inspect库,用于inspect live object。下面的代码是inspect中getmembers函数的源代码,从官方的代码中我们就可以发现docstring和comment的区别了
def getmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name.Optionally, only return members that satisfy a given predicate."""
if isclass(object):
mro = (object,) + getmro(object)
else:
mro = ()
results = []
processed = set()
names = dir(object)
# :dd any DynamicClassAttributes to the list of names if object is a class;
# this may result in duplicate entries if, for example, a virtual
# attribute with the same name as a DynamicClassAttribute exists
try:
for base in object.__bases__:
for k, v in base.__dict__.items():
if isinstance(v, types.DynamicClassAttribute):
names.append(k)
except AttributeError:
pass
for key in names:
# First try to get the value via getattr. Some descriptors don't
# like calling their __get__ (see bug #1785), so fall back to
# looking in the __dict__.
try:
value = getattr(object, key)
# handle the duplicate key
if key in processed:
raise AttributeError
except AttributeError:
for base in mro:
if key in base.__dict__:
value = base.__dict__[key]
break
else:
# could be a (currently) missing slot member, or a buggy
# __dir__; discard and move on
continue
if not predicate or predicate(value):
results.append((key, value))
processed.add(key)
results.sort(key=lambda pair: pair[0])
return results
我们可以看到,最顶上的docstring介绍了我们应该怎么使用这个函数,包括参数是什么,返回类型是什么,返回的值是怎样的等等。这里的docstring完全没有提到这个函数是如何实现的,但是对于只是想知道怎么使用这个getmembers函数的人来讲,这个docstring完全足够了
在函数内部还有很多注释,如果我们观察这些注释,我们会发现,这些注释里面记录的都是函数具体实现的细节
如果你需要弄懂函数是怎么工作的,这些注释就会非常有用,但是如果你只需要知道该怎么用这个函数,那么看docstring就足够了
抛砖引玉,以下为个人理解
注释会被忽略
文档字符串(doctoring)可以被调用(不影响程序的执行)
比如我有个叫hello.py的Python文件,内容如下
def say_hello():
"""Print hello world to console"""
print('hello, world') # Say 'hello, world'
if __name__ == '__main__':
say_hello()
那么我可以在Python Interactive Shell里面执行如下操作,查看say_hello函数的docstring
>>> import hello
>>> hello.say_hello()
hello, world
>>> help(hello.say_hello)
Help on function say_hello in module hello:
say_hello()
Print hello world to console