如何注释运算符之间的大型赋值?

2024-09-28 21:53:08 发布

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

fontName  = b"\xC8\xC1\x10" \
            # Representación del tipo de fuente en bytes.
          + fontNamesInBytes[fontName] \
            # Tipo de atributo: attr_ubyte | Atributo: FontName (Nº 168)
          + "\xF8\xA8"

python3 test.py
  File "test.py", line 14
    + fontNamesInBytes[fontName] \
    ^
IndentationError: unexpected indent

python3 test.py
  File "test.py", line 13
    \# Representación del tipo de fuente en bytes.\
                                                   ^
SyntaxError: unexpected character after line continuation character

python3 test.py
  File "test.py", line 15
    """ Tipo de atributo: attr_ubyte | Atributo: FontName (Nº 168)"""\
                                                                     ^
SyntaxError: invalid syntax

有什么方法可以让我在作业之间发表评论吗?我试过""" """,但也给出了语法错误。你知道吗

为马丁编辑:

fontName  = b"\xC8\xC1\x10" \
          """ Representación del tipo de fuente en bytes."""\
          + fontNamesInBytes[fontName] \
          """ Tipo de atributo: attr_ubyte | Atributo: FontName (Nº 168) """\
          + b"\xF8\xA8"

    python3 test.py
  File "test.py", line 15
    """ Tipo de atributo: attr_ubyte | Atributo: FontName (Nº 168) """\
                                                                      ^
SyntaxError: invalid syntax

Tags: pytestlinedepython3fileattrdel
2条回答

你能做到的

In [5]: ('a'
   ...: # comment
   ...: 'b')
Out[5]: 'ab'

你的代码会变成

fontName  = (b"\xC8\xC1\x10" 
             # Representación del tipo de fuente en bytes.
             + fontNamesInBytes[fontName] +
             # Tipo de atributo: attr_ubyte | Atributo: FontName (Nº 168)
             b"\xF8\xA8")

这是因为括号、方括号或大括号中的表达式可以拆分为多个物理行,而无需使用反斜杠,隐式连续行可以携带注释(根据documentation)。你知道吗

您不能像这样在语句之间放置注释,因为\有效地删除了换行符。因此,#之后的所有文本都是注释,不再是表达式的一部分。你知道吗

您可以将表达式放在括号中:

fontName = (
    b"\xC8\xC1\x10"
    # Representación del tipo de fuente en bytes.
    + fontNamesInBytes[fontName]
    # Tipo de atributo: attr_ubyte | Atributo: FontName (Nº 168)
    + b"\xF8\xA8")

现在注释被视为单独的行,但是解析器继续扩展表达式,直到结束)。通过使用括号,您仍然可以保留新行,这对于在注释结束和表达式继续时发出信号至关重要。你知道吗

为了理解差异,研究Line structure documentation;一个表达式应该形成一个逻辑行,但通常只允许一个物理行。但是在括号内,物理换行符被忽略,允许implicit line joining

Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.

[...]

Implicitly continued lines can carry comments

相关问题 更多 >