2017-04-15 10 views
2

"Crash Course in Python"という本から、(v3.6を使用して)Pythonを学習しています。最後の章では、私はこの例題に出くわしましたが、実行するとエラーになります。私は何が間違っているのかを提案してください。私はそれを理解することはできません。 注:両方のプログラムは同じフォルダにあります。インスタンスメソッドの変数を参照するNameError

**survey.py** 
class AnonymousSurvey(): 
    def __init__(self, question): 
     """Store a question, and prepare to store responses.""" 
     self.question = question 
     self.responses = [] 

    def show_question(self): 
     """Show the survey question.""" 
     print(question) 

    def store_response(self, new_response): 
     """Store a single response to the survey.""" 
     self.responses.append(new_response) 

    def show_results(self): 
     """Show all the responses that have been given.""" 
     print("Survey results:") 
     for response in responses: 
      print('- ' + response) 


**Survey class use** 

from survey import AnonymousSurvey 

question="What languages so you know?" 
my_survey = AnonymousSurvey(question) 
my_survey.show_question() 

print("Enter 'q' at any time to quit.\n") 
while True: 
    response = input("Language: ") 
    if response == 'q': 
     break 
    my_survey.store_response(response) 

# Show the survey results. 
print("\nThank you to everyone who participated in the survey!") 
my_survey.show_results() 

ERROR: 

Traceback (most recent call last): 
    File "survey_usage.py", line 6, in <module> 
    my_survey.show_question() 
    File "C:\Users\xyz\Desktop\python_training\Chapter 11\survey.py", line 10, in show_question 
    print(question) 
NameError: name 'question' is not defined 
+0

「self.question」を含める必要があります。 – Li357

答えて

1

あなたはself.question、ないquestion印刷したいです。一般に、クラス内のインスタンス変数にアクセスするときは、明示的にselfを使用する必要があります。

+0

ありがとうございます。それは「質問」のためにnameErrorの世話をするが、今これを見ていた:調査結果: トレースバック(最新の呼び出しの最後): my_survey.show_resultsで ファイル「survey_usage.py」、17行目、() ファイル「C :\ Users \ xyz \ Desktop \ python_training \ Chapter 11 \ survey.py "、行19、show_results NameError:name 'responses'は定義されていません – anna

+0

これは同じことです。 ''レスポンス 'ではなく、' respond'ではなく、 '' self''を使ってクラスのインスタンス変数を明示的に参照する必要があるからです。 –

+0

あなたは私を誤解しました。 'self.response'は何もありません。 'self.responses'はあなたが定義したクラス変数であったため、' self.responses'で 'for response 'が必要です。 'response'はローカルスコープで宣言されました。 「自己」は必要ありません。 –