python - Python 中单行代码的长注释

标签 python comments

尽管读过什么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/

相关文章:

python - 如何通过 Selenium python 登录到 yahoo(尝试了多种解决方案)

python - Matplotlib:对数图中奇怪的双十年轴刻度

python - 使用 Airflow 迁移大型表

python - 更改键盘快捷键以注释 Spyder 中的行

Python NOOP 替换

python - 如何使用Opencv缩小/扩大面部特征?

python - 任何人都知道检测两个字符串之间相似程度的有效机制

c - 如何使用 Perl 将 C 注释从一行的开头移动到结尾?

css - 添加评论时,WordPress 侧边栏会下降到页面底部

c++ - 有没有更好的方法在代码中注释参数的方向?