如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
从公认的答案…
你可以使用三引号字符串。当它们不是文档字符串(类/函数/模块中的第一件事)时,它们将被忽略。
这是不正确的。与注释不同,三引号字符串仍然被解析,并且必须在语法上有效,无论它们出现在源代码中的哪个位置。
如果你试图运行这段代码…
def parse_token(token):
"""
This function parses a token.
TODO: write a decent docstring :-)
"""
if token == '\\and':
do_something()
elif token == '\\or':
do_something_else()
elif token == '\\xor':
'''
Note that we still need to provide support for the deprecated
token \xor. Hopefully we can drop support in libfoo 2.0.
'''
do_a_different_thing()
else:
raise ValueError
你会得到…
ValueError: invalid \x escape
...Python 2。x或…
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...Python 3.x。
做被解析器忽略的多行注释的唯一方法是…
elif token == '\\xor':
# Note that we still need to provide support for the deprecated
# token \xor. Hopefully we can drop support in libfoo 2.0.
do_a_different_thing()
其他回答
不幸的是,字符串化不能总是用于注释!因此,坚持在每行前加上#的标准更安全。
这里有一个例子:
test1 = [1, 2, 3, 4,] # test1 contains 4 integers
test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
我建议不要在多行注释中使用“”!
这里有一个简单的例子来强调可能被认为是意外的行为:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
现在看一下输出:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
多行字符串不被视为注释,但它与'显然我也是一个字符串'连接起来,形成一个单一的字符串。
如果您想注释多行,请根据PEP 8指南执行:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
输出:
I am a string
clearly I am also a string
你可以使用三引号字符串。当它们不是docstring(类/函数/模块中的第一件事)时,它们将被忽略。
'''
This is a multiline
comment.
'''
(确保适当缩进前导" '以避免出现IndentationError。)
Guido van Rossum (Python的创造者)在推特上发布了这条“专业提示”。
然而,Python的风格指南PEP8倾向于使用连续的单行注释,像这样:
# This is a multiline
# comment.
...这也是你在很多项目中会发现的。文本编辑器通常有一个快捷方式来轻松做到这一点。
在Python 2.7中,多行注释是:
"""
This is a
multilline comment
"""
如果你在一个类中,你应该正确地制表。
例如:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
从公认的答案…
你可以使用三引号字符串。当它们不是文档字符串(类/函数/模块中的第一件事)时,它们将被忽略。
这是不正确的。与注释不同,三引号字符串仍然被解析,并且必须在语法上有效,无论它们出现在源代码中的哪个位置。
如果你试图运行这段代码…
def parse_token(token):
"""
This function parses a token.
TODO: write a decent docstring :-)
"""
if token == '\\and':
do_something()
elif token == '\\or':
do_something_else()
elif token == '\\xor':
'''
Note that we still need to provide support for the deprecated
token \xor. Hopefully we can drop support in libfoo 2.0.
'''
do_a_different_thing()
else:
raise ValueError
你会得到…
ValueError: invalid \x escape
...Python 2。x或…
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...Python 3.x。
做被解析器忽略的多行注释的唯一方法是…
elif token == '\\xor':
# Note that we still need to provide support for the deprecated
# token \xor. Hopefully we can drop support in libfoo 2.0.
do_a_different_thing()