如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
我建议不要在多行注释中使用“”!
这里有一个简单的例子来强调可能被认为是意外的行为:
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
其他回答
Visual Studio Code通用官方多行注释切换。类似于Xcode的快捷方式。
macOS:选择code-block,然后选择⌘+/
Windows:选择code-block,然后按Ctrl+/
你可以使用三引号字符串。当它们不是docstring(类/函数/模块中的第一件事)时,它们将被忽略。
'''
This is a multiline
comment.
'''
(确保适当缩进前导" '以避免出现IndentationError。)
Guido van Rossum (Python的创造者)在推特上发布了这条“专业提示”。
然而,Python的风格指南PEP8倾向于使用连续的单行注释,像这样:
# This is a multiline
# comment.
...这也是你在很多项目中会发现的。文本编辑器通常有一个快捷方式来轻松做到这一点。
我阅读了各种方法的缺点,我想出了这个方法,试图检查所有的盒子:
block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
def __init__(self):
# create the event object inside raising class
self.on_thing_happening = Event()
def doing_something(self):
# raise the event inside the raising class
self.on_thing_happening()
class ExampleEventHandlingClass():
def __init__(self):
self.event_generating_thing = ExampleEventSource()
# add event handler in consuming class
event_generating_thing.on_thing_happening += my_event_handler
def my_event_handler(self):
print('handle the event')
]#'''
class Event():
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
Pros
对于其他程序员来说,这显然是一个注释。这是自描述的。 它编译 它不会在help()中显示为doc注释 如果需要,它可以位于模块的顶部 它可以通过宏自动实现。 [注释]不是代码的一部分。它不会在pyc中结束。(除了支持优点#1和#4的一行代码) 如果在Python中添加了多行注释语法,则可以使用find和replace修复代码文件。简单地使用“”并没有这个优势。
Cons
很难记住。打字量很大。这个骗局可以用宏来消除。 这可能会让新手感到困惑,认为这是惟一的块注释方法。这可能是专业的,只是取决于你的角度。它可能会让新手认为这行代码神奇地连接到注释“working”。 它不会作为注释着色。但话又说回来,没有一个答案能真正解决OP问题的精神。 这不是官方的方式,所以Pylint可能会抱怨。我不知道。也许;也许不是。
这里是一个VS Code宏的尝试,尽管我还没有测试它:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}
多行注释实际上在Python中并不存在。下面的示例包含一个未赋值的字符串,Python将验证该字符串是否存在语法错误。
一些文本编辑器,如notepad++,为我们提供了注释掉一段书面代码或单词的快捷方式。
def foo():
"This is a doc string."
# A single line comment
"""
This
is a multiline
comment/String
"""
"""
print "This is a sample foo function"
print "This function has no arguments"
"""
return True
此外,Ctrl + K是notepad++中阻止注释的快捷键。它在选定的每一行前面添加一个#。Ctrl + Shift + K表示取消注释。
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)