尽管已经阅读了 PEP8对评论主题的评论,但我仍然想知道如何最好地评论Python中的单行代码.
当所讨论的代码行(非常)很短时,给出的示例很好:
x = x + 1 # Compensate for border
Run Code Online (Sandbox Code Playgroud)
但如果行或评论更长,则事情变得更加困难.例如:
import numpy as np
import matplotlib.pyplot as plt
a = np.random.random([3, 3])
b = np.random.random([3, 3])
coords = zip(a.ravel(), b.ravel()) # match elements of a with elements of b ignoring shape
plt.scatter(*zip(*coords))
Run Code Online (Sandbox Code Playgroud)
注释相当长,代码行也是如此,使得整个事情比可接受的行长度更长.
我通常把评论放在上面,但是不清楚评论是否适用于该plt行:
# match elements of a with elements of b ignoring shape
coords = zip(a.ravel(), b.ravel())
plt.scatter(*zip(*coords))
Run Code Online (Sandbox Code Playgroud)
我倾向于通过在两行之间插入换行来解决这个问题:
# match elements of a with elements of b ignoring shape
coords = zip(a.ravel(), b.ravel())
plt.scatter(*zip(*coords))
Run Code Online (Sandbox Code Playgroud)
我也这样做了,但似乎有点过分了:
"""
match elements of a with elements
of b ignoring shape
"""
# ================================
coords = zip(a.ravel(), b.ravel())
# ================================
plt.scatter(*zip(*coords))
Run Code Online (Sandbox Code Playgroud)
这是否有可接受的方式?
我最常看到的风格是将注释放在上面一行。在大多数情况下,阅读您代码的人会理解记录的行为何时结束。如果不清楚引用行下面的代码的作用,也许它也需要注释。
我也会尝试浓缩我的评论。代替:
# match elements of a with elements of b ignoring shape
coords = zip(a.ravel(), b.ravel())
Run Code Online (Sandbox Code Playgroud)
我会写:
coords = zip(a.ravel(), b.ravel()) # match elements of a and b, ignore shape
Run Code Online (Sandbox Code Playgroud)
对于 PEP8 来说这已经足够短了。尽管对于更长的线路来说这可能是不可能的。