2016-09-06 11 views
-2

私はPythonの初心者です。以下はコードです。オブジェクトに指定された属性のエラーがPythonにありません

class simple: 
    def __init__(self, str): 
     print("inside the simple constructor") 
     self.s = str 


# two methods: 

def show(self): 
    print(self.s) 

def showMsg(self, msg): 
    print(msg + ":", self.show()) 


if __name__ == "__main__": 
    # create an object: 
    x = simple("constructor argument") 

    x.show() 
    x.showMsg("A message") 

私はそれを実行した後、私はそう

AttributeError: 'simple' object has no attribute 'show' 

を持って、誰もがここで何が起こっているか知っているのですか? 'show'は属性ではありません。私の理解のために、それは方法でなければならない。誰がここで起こっていることを理解していますか?あなたの時間と注意に感謝します。

+2

インデントはPythonでは必要です。インスタンスメソッドがクラス内にあることを確認してください。 – idjaw

答えて

1

インタプリタにそのクラスの一部であることを通知するには、メソッドをインデントする必要があります。それ以外の場合は、スタンドアロン機能を作成するだけです。あなたが望んでいた場合

class simple: 
    def __init__(self, str): 
     print("inside the simple constructor") 
     self.s = str 

    # two methods: 
    # note how they are indented 

    def show(self): 
     print(self.s) 

    def showMsg(self, msg): 
     print(msg + ":", self.show()) 

if __name__ == "__main__": 
    # create an object: 
    x = simple("constructor argument") 

    x.show() 
    x.showMsg("A message") 

技術的には、あなたの代わりにx.show()show(x)を使用して、とにかく、インデントバージョンの仕事を作ることができるが、上記のようにインデントを修正するために明確になるだろう。

関連する問題