【问题标题】:Python: Whats wrong with this class definition (indentation error)Python:这个类定义有什么问题(缩进错误)
【发布时间】:2012-01-11 21:01:05
【问题描述】:

我似乎看不出这段代码有什么问题,但我在运行脚本时收到 IndentationError

import web
import json

urls = (
    '/(.*)', 'handleRequest'
)
app = web.application(urls, globals())

class handleRequest:
    def GET(self, method_id):
        if not method_id: 
            return json.dumps({'ok':0})
        else:
            return json.dumps({'ok': method_id})

    def POST(self):
        i = web.input()
        pass

if __name__ == "__main__":
    app.run()

这是我尝试运行脚本时收到的控制台错误消息:

>>>     def POST(self):
  File "<stdin>", line 1
    def POST(self):
    ^
IndentationError: unexpected indent
>>>         i = web.input()
  File "<stdin>", line 1
    i = web.input()
    ^

我已经检查了缩进 - 以及我在整个文件中使用的相同 4 个空格 - 我错过了什么吗?!

【问题讨论】:

    标签: python


    【解决方案1】:

    您不是在“运行脚本”,而是将其输入到 REPL 中。将内容保存到文件并通过例如执行文件python somescript.py.

    【讨论】:

    • 你是对的 - 似乎 VIM 在“粘贴”操作期间插入了一些非空格(但不可见)字符。经验教训。
    【解决方案2】:

    GET 的结尾和POST 的开头之间的行没有缩进。

    这在 python 执行文件时应该没问题,但是当输入 REPL 时(如您所见),python 将空行作为类 handleRequest 的结尾

    【讨论】:

      【解决方案3】:

      您是否将其粘贴到交互式会话中?您的方法之间不能有换行符(空行告诉解释器该类已完成)

      【讨论】:

        猜你喜欢
        • 2022-08-15
        • 2015-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-12
        相关资源
        最近更新 更多