1

我是 python 新手。我正在尝试运行以下程序:

class Temp():

    def __init__(self):
        print 'hello world!'

    def main():
        temp = Temp()
        print 'here i am'

    if __name__ == '__main__':
        main()

我收到此错误:

Traceback (most recent call last):
File "test.py", line 1, in <module>
  class Temp():
File "test.py", line 11, in Temp
  main()
File "test.py", line 7, in main
  temp = Temp()

为什么我收到此错误?

4

1 回答 1

4

Unndentmain()和它下面的东西,现在它是一种Temp非独立功能的方法。您实际上是在尝试调用没有Temp.

缩进是 python 如何确定方法、类、循环中的内容。看这里:

编辑

class Temp():
    def __init__(self):
        # this method is in Temp
        pass

    def prettyPrint(self):
        # this method is also in temp
        print("I'm in temp")

def prettyPrint(self):
    #this is not in Temp (notice the indentation change)
    print("I'm not in temp")

if __name__ == "__main__":
    #this is not in temp either
    t = Temp()
    t.prettyPrint()
    prettyPrint(None)
于 2012-09-23T04:43:26.137 回答