如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用Python注释支持#。
我正在使用Anaconda Spyder,它有:
Ctrl + 1 -注释/取消注释 Ctrl + 4 -注释代码块 Ctrl + 5 -取消注释代码块
它可以用#注释/取消注释一行/多行代码。
我觉得这是最简单的。
例如,一个块注释:
# =============================================================================
# Sample Commented code in spyder
# Hello, World!
# =============================================================================
其他回答
如果你写了评论
"""
long comment here
"""
在脚本中间,Python/linters不会识别它。折叠将是混乱的,因为上面的注释不是标准建议的一部分。用起来更好
# Long comment
# here.
如果你使用Vim,你可以添加像评论这样的插件。通过按Vjgcc自动注释掉长行注释。其中Vj选择了两行代码,gcc将它们注释掉。
如果你不想使用像上面这样的插件,你可以使用搜索和替换
:.,.+1s/^/# /g
这将用#替换当前和下一行的第一个字符。
我阅读了各种方法的缺点,我想出了这个方法,试图检查所有的盒子:
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表示取消注释。
是的,两者都可以使用:
'''
Comments
'''
and
"""
Comments
"""
但是,在IDE中运行时,你需要记住的唯一一件事是,你必须“运行”整个文件,以接受多行代码。逐行“RUN”将无法正常工作,并将显示错误。
Python 2.7.13:
单:
"A sample single line comment "
多行:
"""
A sample
multiline comment
on PyCharm
"""