python - 类 python 中的 IndentationError

标签 python python-3.x indentation

<分区>

我有这样的代码

# -*- 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 行,但让我大吃一惊

最佳答案

这是您的代码,其中空格被点替换:

#.-*-.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).

关于python - 类 python 中的 IndentationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49951867/

相关文章:

python - 为什么在 python 中允许浮点切片 (slice(0,1,0.1)),但调用索引方法 (slice(0,1,0.1).indices) 会引发 TypeError?

python - pandas 使用 groupby 变换创建 bool 列

Python函数缩进错误: unexpected indent

bash - bash 脚本的正确缩进是什么?

Python 字符串 in...in 语法

Python wave : Extracting stereo channels separately from *. wav 文件

python - 我正在尝试使用 python 从 postgresql 中的列中提取值。但我总是收到此错误 :

mongodb - 如何使用 ssh 创建 mongoengine 连接?

vim - 如何在 VIM 中启用文件特定的选项卡缩进设置?

java - 如何让 Jython 脚本同步调用 Java 方法?