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

Unindentmain()とその下にあるものは、現在、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 に答える