Python中单行代码的长注释

2024-04-23 06:45:44 发布

您现在位置:Python中文网/ 问答频道 /正文

尽管我已经阅读了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))

有没有公认的方法?你知道吗


Tags: of代码importmatchwithnppltrandom
1条回答
网友
1楼 · 发布于 2024-04-23 06:45:44

我看到最多的风格是把评论放在上面一行。在大多数情况下,阅读您的代码的人会理解记录的行为何时结束。如果不清楚引用行下面的代码是做什么的,可能也需要注释。你知道吗

我也会尽量压缩我的评论。而不是:

# 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来说足够短了。虽然这可能不可能与较长的线。你知道吗

相关问题 更多 >