如何做多行注释?大多数语言都有块注释符号,比如:

/*

*/

当前回答

你可以使用下面的方法。这叫做DockString。

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__

其他回答

从公认的答案…

你可以使用三引号字符串。当它们不是文档字符串(类/函数/模块中的第一件事)时,它们将被忽略。

这是不正确的。与注释不同,三引号字符串仍然被解析,并且必须在语法上有效,无论它们出现在源代码中的哪个位置。

如果你试图运行这段代码…

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()

AFAIK, Python没有块注释。对于注释单个行,可以使用#字符。

如果你正在使用notepad++,有一个块注释的快捷方式。我相信其他的像gVim和Emacs也有类似的特性。

在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用Python注释支持#。

我正在使用Anaconda Spyder,它有:

Ctrl + 1 -注释/取消注释 Ctrl + 4 -注释代码块 Ctrl + 5 -取消注释代码块

它可以用#注释/取消注释一行/多行代码。

我觉得这是最简单的。

例如,一个块注释:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

是的,两者都可以使用:

'''
Comments
'''

and

"""
Comments
"""

但是,在IDE中运行时,你需要记住的唯一一件事是,你必须“运行”整个文件,以接受多行代码。逐行“RUN”将无法正常工作,并将显示错误。

Visual Studio Code通用官方多行注释切换。类似于Xcode的快捷方式。

macOS:选择code-block,然后选择⌘+/

Windows:选择code-block,然后按Ctrl+/