其他答案在這裏已經指出,可能與Sphinx way一起使用,以便您可以使用Sphinx在稍後生成那些奇特的文檔。
這就是說,我個人會偶爾使用內聯評論風格。
def complex( # Form a complex number
real=0.0, # the real part (default 0.0)
imag=0.0 # the imaginary part (default 0.0)
): # Returns a complex number.
"""Form a complex number.
I may still use the mainstream docstring notation,
if I foresee a need to use some other tools
to generate an HTML online doc later
"""
if imag == 0.0 and real == 0.0:
return complex_zero
other_code()
這裏再舉一個例子,有一些微小的細節記錄在線:
def foo( # Note that how I use the parenthesis rather than backslash "\"
# to natually break the function definition into multiple lines.
a_very_long_parameter_name,
# The "inline" text does not really have to be at same line,
# when your parameter name is very long.
# Besides, you can use this way to have multiple lines doc too.
# The one extra level indentation here natually matches the
# original Python indentation style.
#
# This parameter represents blah blah
# blah blah
# blah blah
param_b, # Some description about parameter B.
# Some more description about parameter B.
# As you probably noticed, the vertical alignment of pound sign
# is less a concern IMHO, as long as your docs are intuitively
# readable.
last_param, # As a side note, you can use an optional comma for
# your last parameter, as you can do in multi-line list
# or dict declaration.
): # So this ending parenthesis occupying its own line provides a
# perfect chance to use inline doc to document the return value,
# despite of its unhappy face appearance. :)
pass
的好處(如@標記霍瓦特已在其它評論指出)是:
- 最重要的是,參數和他們的文檔始終保持在一起,這帶來以下好處:
- 減少打字(無需重複變量名稱)
- 更改/刪除變量時更易於維護。重命名某些參數後,絕不會有一些孤兒參數doc段落。
- 和更容易找到缺少的評論。
現在,有人可能會認爲這種風格看起來很「醜陋」。但我會說「醜」是一個主觀詞。更加中性的方式是說,這種風格不是主流,所以它可能看起來不太熟悉,因此不太舒服。再次,「舒適」也是一個主觀詞彙。但重要的是,上述所有的好處都是客觀的。你不能以標準的方式實現它們。
希望未來有一天,會有一個文檔生成器工具,它也可以使用這種內聯樣式。這將推動採用。
PS:這個答案來源於我自己喜歡的每當我認爲合適時使用內嵌評論。我也使用same inline style to document a dictionary。
你讀過PEP 257? http://www.python.org/dev/peps/pep-0257/ – NPE 2012-02-08 14:47:37
這裏有幾個「標準」,但實際的方法,特別是如果你喜歡正式的東西,我會建議[獅身人面像](http:///pythonhosted.org/an_example_pypi_project/sphinx.html)。它在[Pycharm](https://www.jetbrains.com/pycharm/)中的集成使生成結構良好的文檔字符串非常輕鬆。恕我直言 – jojo 2014-06-24 09:24:55