如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
我认为它没有,除了一个多行字符串没有被处理。然而,大多数(如果不是所有的话)Python ide都有一个短键来“注释掉”多行代码。
其他回答
从公认的答案…
你可以使用三引号字符串。当它们不是文档字符串(类/函数/模块中的第一件事)时,它们将被忽略。
这是不正确的。与注释不同,三引号字符串仍然被解析,并且必须在语法上有效,无论它们出现在源代码中的哪个位置。
如果你试图运行这段代码…
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()
Python中的内嵌注释以哈希字符开始。
hello = "Hello!" # This is an inline comment
print(hello)
你好!
注意,字符串文字中的哈希字符只是一个哈希字符。
dial = "Dial #100 to make an emergency call."
print(dial)
拨打100拨打紧急电话。
散列字符也可以用于单行或多行注释。
hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)
你好 世界
用三双引号将文本括起来以支持docstring。
def say_hello(name):
"""
This is docstring comment and
it's support multi line.
:param name it's your name
:type name str
"""
return "Hello " + name + '!'
print(say_hello("John"))
你好约翰!
在文本中加上三个单引号作为块注释。
'''
I don't care the parameters and
docstrings here.
'''
是的,两者都可以使用:
'''
Comments
'''
and
"""
Comments
"""
但是,在IDE中运行时,你需要记住的唯一一件事是,你必须“运行”整个文件,以接受多行代码。逐行“RUN”将无法正常工作,并将显示错误。
Visual Studio Code通用官方多行注释切换。类似于Xcode的快捷方式。
macOS:选择code-block,然后选择⌘+/
Windows:选择code-block,然后按Ctrl+/
Python中的多行注释:
对我来说,“’”和“”都管用。
例子:
a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)
例子:
a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)