有没有办法将文档字符串与它们所描述的函数分开?
我正在做一个模块,这个模块里有很多小功能,但是它们的文档字符串(docstrings)往往很长。这些长长的文档字符串让我在使用这个模块时很烦,因为我总是要不停地滚动,才能找到一点实际的代码。
有没有办法把文档字符串和它们所描述的功能分开呢?我真的希望能把文档字符串放在文件的最后,远离代码,或者更好的是,放在一个单独的文件里。
1 个回答
13
函数的文档字符串可以通过一个特殊的属性 __doc__
来访问。
>>> def f(x):
... "return the square of x"
... return x * x
>>> f.__doc__
'return the square of x'
>>> help(f)
(help page with appropriate docstring)
>>> f.__doc__ = "Return the argument squared"
>>> help(f)
(help page with new docstring)
这展示了这个技巧。实际上,你可以:
def f(x):
return x * x
f.__doc__ = """
Return the square of the function argument.
Arguments: x - number to square
Return value: x squared
Exceptions: none
Global variables used: none
Side effects: none
Limitations: none
"""
...或者你想放在文档字符串里的任何内容。