0

我的 Python 代码如下所示:

'''
a) comments
'''
try:
  do_stuff()

'''
b) comments
'''
except Error:
  do_stuff()

但它抱怨 (b) 注释是一个语法错误 - 它迫使我像这样缩进它:

'''
a) comments
'''
try:
  do_stuff()

  '''
  b) comments
  '''
except Error:
  do_stuff()

为什么会这样,我该如何解决?我希望 (b) 评论与他们描述的“除外”声明处于同一水平。

谢谢

4

3 回答 3

3

三引号实际上是字符串,而不是注释。

所以你需要相应地缩进字符串,(因为每个冒号 ( :) 必须紧跟一个缩进块)

于 2013-08-13T00:12:32.073 回答
2

Normally, the triple quotes are used for multiline strings or docstrings, which appear only at the beginning of the function/class/module that you are documenting.

When not writing docstrings, I would recommend that you use the normal comment syntax:

# this is a comment

Also, if you want to have docstrings, convention dictates that you use triple double quotes: """, not '''

于 2013-08-13T00:17:34.090 回答
0

首先,它不是注释,而是字符串,所以你真正想要做的是不同的。Indent 和 dedent 就像其他一些语言中的开括号和右括号,所以你真正在做什么(在类似 PHP 的语法中):

try {
    $some_string = 'a) comments';
    do_stuff();
} // notice closing bracket, which works like decreased indent
$some_string = 'b) comments';
catch (Error $e) {
    do_stuff();
}

尝试使用真实的评论:

# a) comments
try:
    do_stuff()

# b) comments
except Error:
    do_stuff()

Demo: http://ideone.com/CxU56R

于 2013-08-13T00:16:31.547 回答