在Python中创建多行注释的方法?

问题描述 投票:1004回答:19

我最近开始研究Python,但我找不到如何实现多行注释。大多数语言都有块注释符号

/* 

*/

我在Python中试过这个,但它会抛出一个错误,所以这可能不是正确的方法。 Python实际上是否具有多行注释功能?

python python-3.x python-2.7 comments documentation
19个回答
1634
投票

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

'''
This is a multiline
comment.
'''

(确保适当地缩进领先的'''以避免使用IndentationError。)

Guido van Rossum(Python的创造者)tweeted this作为“职业提示”。

但是,Python的样式指南,PEP8,favors using consecutive single-line comments,这也是你在许多项目中都能找到的。编辑通常有一个快捷方式来轻松完成这项工作。


4
投票

不幸的是,字符串化并不总是可以用作评论!因此,坚持使用#在每行前面的标准是更安全的。

这是一个例子:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

2
投票

在Python 2.7.13上:

单:

"A sample single line comment "

多行:

"""
A sample
multiline comment
on PyCharm
"""

2
投票

python中的内联注释以哈希哈希字符开头。

hello = "Hello!" # this is 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 params and
docstrings here.
'''

0
投票

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用于块取消注释。


0
投票

使用PyCharm IDE。

您可以使用Ctrl + /来commentuncomment代码行。 Ctrl + /注释或取消注释当前行或多行选定行,单行注释({# in Django templates, or # in Python scripts)Pressing Ctrl+Shift+/用于Django模板中选定的源代码块,用{% comment %} and {% endcomment %}标签围绕块。


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

选择所有行然后按Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

0
投票

要在Python中注释掉多行代码,只需在每一行使用#单行注释:

# This is comment 1
# This is comment 2 
# This is comment 3

对于在Python中编写“正确”的多行注释,可以使用带有"""语法的多行字符串Python具有文档字符串(或docstrings)功能。它为程序员提供了一种简单的方法,可以为每个Python模块,函数,类和方法添加快速注释。

'''
This is
multiline
comment
'''

另外,请提及您可以通过类对象访问docstring

myobj.__doc__

0
投票

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)

0
投票

是的,两者兼而有之

'''
Comments
'''

""" 
Comments
"""

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


-2
投票

选择要评论的行,然后使用“CTRL +?”在sublime编辑器中注释或取消注释python代码。对于单行,您可以使用'shift +#'。


76
投票

Python确实有一个multiline string/comment syntax,除非用作文档字符串,multiline strings generate no bytecode - 就像#-prepended评论一样。实际上,它的行为与评论完全相同。

另一方面,如果你说这个行为必须在官方文档中记录为真正的注释语法,那么是的,你说这不是作为语言规范的一部分保证是正确的。

在任何情况下,您的编辑器也应该能够轻松地注释掉所选区域(通过在每条线的前面放置一个#)。如果没有,请切换到可执行的编辑器。

没有特定文本编辑功能的Python编程可能是一种痛苦的经历。找到正确的编辑器(以及知道如何使用它)可以对Python编程体验的感知方式产生重大影响。

编辑器不仅能够注释掉所选区域,而且还应该能够轻松地向左右移动代码块,并且当您按Enter键时应自动将光标置于当前缩进级别。代码折叠也很有用。


为了防止链路衰减,这里是Guido van Rossum's tweet的内容:

@BSUCSClub Python技巧:您可以使用多行字符串作为多行注释。除非用作文档字符串,否则它们不会生成代码! :-)


38
投票

从接受的答案......

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

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

如果您尝试运行此代码...

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

31
投票

在Python 2.7中,多行注释是:

"""
This is a
multilline comment
"""

如果你在一个类中,你应该正确地选中它。

例如:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

25
投票

AFAIK,Python没有块注释。要评论单个行,您可以使用#字符。

如果你正在使用Notepad++there is a shortcut for block commenting。我敢肯定像gVimEmacs这样的人也有类似的功能。


12
投票

我认为它没有,除了不处理多行字符串。但是,大多数(如果不是所有)Python IDE都有一个用于“注释掉”多行代码的快捷键。


7
投票

如果你发表评论

"""
long comment here
"""

在脚本中间,python / linters将无法识别。折叠将被搞砸,因为上述评论不是标准建议的一部分。它更好用

# long comment
# here.

如果你使用vim,你可以插件像https://github.com/tpope/vim-commentary,通过按Vjgcc自动注释掉长行注释。 Vj选择2行代码,gcc将其注释掉。

如果你不想使用上面的插件你可以使用搜索和替换之类的

:.,.+1s/^/# /g

这将用#替换当前和下一行的第一个字符。


7
投票

多行评论没有这样的功能。 #是评论单行代码的唯一方法。很多人回答'''评论''这是他们的解决方案。虽然它似乎工作但在python中内部'''将包含的行作为常规字符串,解释器不会忽略使用#的注释。

Check official documentation here


4
投票

好吧,你可以尝试这个(当运行引用时,第一个问题的输入应该引用'):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

无论"""之间的任何内容都会被评论。

如果您正在寻找单行评论,那么它就是#

© www.soinside.com 2019 - 2024. All rights reserved.