python类定义 - 名称未定义或意外缩进

时间:2013-05-14 00:50:18

标签: python class

class Animal(object):

        """Makes cute animals."""
        is_alive = True
        def __init__(self, name, age):
        self.name = name
        self.age = age
    # Add your method here!
    def description(self):
        print self.name
        print self.age

hippo = Animal("Steve",100) 
hippo.description() 

- 代码片段

我得到的错误:

Traceback (most recent call last):
  File "runner.py", line 125, in compilecode
  File "python", line 3
    is_alive = True
   ^
IndentationError: unexpected indent

不知道发生了什么

谁能告诉我哪里错了? 非常感谢!

3 个答案:

答案 0 :(得分:3)

看起来你正在混合制表符和空格。这意味着看作缩进的内容,以及解释器看到的内容,完全不同。这将导致难以注意IndentationError s。

特别是:

        """Makes cute animals."""
        is_alive = True
        def __init__(self, name, age):
        self.name = name

前两行有8个空格。第三个有7个空格和一个标签。我不确定Python是否将其视为比8个空格更多缩进 - 这是一个错误,因为没有理由在这里缩进 - 或者只是拒绝猜测哪个算法比另一个更加缩进。但不管怎样,这都是错的。然后下一行有两个标签。

要修复此代码,请删除所有标签,然后使用空格重新缩进。

将来避免这种情况的简单方法是永远不要在代码中使用制表符。

您也可以考虑使用更好的编辑器,即使您按Tab键也会始终插入空格。或者,如果失败了,至少和编辑器可以显示标签,这样你就可以在出现问题时发现它们。

最后,当代码看起来非常好时,只要您获得IndentationError,请尝试使用-t标记(python -t myscript.py而非python myscript.py)运行代码,以检查这就是原因。

正如Karl Knechtel在评论中指出的那样,PEP 8(Python风格指南)对此有a section

答案 1 :(得分:0)

你需要缩进self.name和self.age这样的行。

class Animal(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

您必须在您定义的方法下面缩进文字。

答案 2 :(得分:0)

确保您没有混合标签和空格来缩进。选择使用所有选项卡或所有空格。