如何编写多行注释?大多数语言都有块注释符号,例如:
/*
*/
#
。#
来注释/取消注释单行/多行代码。# =============================================================================
# Sample Commented code in spyder
# Hello, World!
# =============================================================================
Ctrl + /
,如果要删除注释,则可以执行相同的操作。
在Mac操作系统中:应该使用command + /
。在Python中注释掉多行代码的方法是在每一行使用 #
单行注释:
# This is comment 1
# This is comment 2
# This is comment 3
"""
语法的多行字符串。Python具有文档字符串(或docstrings)功能。它为程序员提供了一种简单的方式,在每个Python模块、函数、类和方法中添加快速注释。'''
This is
multiline
comment
'''
还有,提一下可以通过类对象访问docstring的方法,像这样
myobj.__doc__
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 + Shift + K则是用于取消块注释。def my_function(arg1):
"""
Summary line.
Extended description of function.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
return arg1
print my_function.__doc__
我了解了各种方法的缺点,并尝试着想出一种方法,以便检查所有的要求:
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)
优点
help()
中不会显示为文档注释。pyc
中。(除了启用优点#1和#4的一行代码)'''
没有这个优势。缺点
Pylint
可能会抱怨。我不知道。也许;也许不。这里是一个VS Code宏的尝试,虽然我还没有测试过:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}
#
作为注释的唯一方式是有道理的。我猜这样做可以让Python脚本更容易被解释。 - Victor Zamanian