尽管读过什么PEP8不得不说关于注释的主题,我仍然想知道如何最好地在 Python 中注释单行代码。
当有问题的代码行(非常)短时,给出的示例很好:
x = x + 1 # Compensate for border
但如果行或评论较长,事情就会变得更加困难。例如:
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))
注释相当长,代码行也很长,使得整个代码行的长度超过了可接受的行长度。
我通常将注释放在该行之上,但不清楚该注释是否适用于 plt
行:
# match elements of a with elements of b ignoring shape
coords = zip(a.ravel(), b.ravel())
plt.scatter(*zip(*coords))
我倾向于通过在两行之间插入一个换行符来解决这个问题:
# match elements of a with elements of b ignoring shape
coords = zip(a.ravel(), b.ravel())
plt.scatter(*zip(*coords))
我也做过这个,不过好像有点夸张了:
"""
match elements of a with elements
of b ignoring shape
"""
# ================================
coords = zip(a.ravel(), b.ravel())
# ================================
plt.scatter(*zip(*coords))
是否有公认的方法来做到这一点?
最佳答案
我似乎看到最多的样式是将注释放在上面一行。在大多数情况下,阅读您的代码的人会理解记录的行为何时结束。如果不清楚引用行下面的代码是做什么的,也许也需要对其进行注释。
我也会尝试浓缩我的评论。而不是:
# match elements of a with elements of b ignoring shape
coords = zip(a.ravel(), b.ravel())
我会写:
coords = zip(a.ravel(), b.ravel()) # match elements of a and b, ignore shape
这对于 PEP8 来说已经足够短了。虽然这对于较长的行可能是不可能的。
关于python - Python 中单行代码的长注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128071/