python类中的IndentationError

2024-04-20 03:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢这样

# -*- coding: utf-8 -*-

class OP(object):

  def RECEIVE_MESSAGE(self):
      print("done")


  def NOTIFIED_INVITE_INTO_GROUP(self):
    print("done")

但是当我运行这个时,我得到了一些错误

Traceback (most recent call last):
File "run.py", line 2, in <module>
  from van import ERVAN
File "/home/server/.pub/van.py", line 4, in <module>
  from op import OP
File "/home/server/.pub/op.py", line 9
  def NOTIFIED_INVITE_INTO_GROUP(self):
                                    ^
IndentationError: unindent does not match any outer indentation level

有什么解决办法吗?它只有10行,但我的头脑


Tags: infrompyselfdeflinegroupinvite
1条回答
网友
1楼 · 发布于 2024-04-20 03:39:52

下面是用点替换空格的代码:

#.-*-.coding:.utf-8.-*-

class.OP(object):

..def.RECEIVE_MESSAGE(self):
......print("done")

..def.NOTIFIED_INVITE_INTO_GROUP(self):
....print("done")

如您所见,第一个print("done")语句缩进了6个空格-将其更改为4以解决问题。你知道吗

更好的是,按照PEP 8的建议,更改所有缩进,使其为4个空格的倍数(即0、4、8、12等)

#.-*-.coding:.utf-8.-*-

class.OP(object):
....def.RECEIVE_MESSAGE(self):
........print("done")

....def.NOTIFIED_INVITE_INTO_GROUP(self):
........print("done")

更多细节,来自Python: Myths about Indentation

How does the compiler parse the indentation? The parsing is well-defined and quite simple. Basically, changes to the indentation level are inserted as tokens into the token stream.

The lexical analyzer (tokenizer) uses a stack to store indentation levels. At the beginning, the stack contains just the value 0, which is the leftmost position. Whenever a nested block begins, the new indentation level is pushed on the stack, and an "INDENT" token is inserted into the token stream which is passed to the parser. There can never be more than one "INDENT" token in a row.

When a line is encountered with a smaller indentation level, values are popped from the stack until a value is on top which is equal to the new indentation level (if none is found, a syntax error occurs).

相关问题 更多 >