私は、クラスを作成し、別のファイルでそのインスタンスを作成することで簡単なアンケートを作成しようとしています。私の問題は、プログラムの開始時に明示的に定義したときに、「質問」変数が定義されていないというエラーが表示されることです。ここではエラーがあります:ここではNameErrorを取得中:変数が定義されていないときに定義されていません
line 11, in show_question print(question)/
NameError: name 'question' is not defined
は私がインスタンス化していたクラスです:
class AnonymousSurvey():
"""Collect anonymous answers to a survey question."""
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)
をそしてここで私が働いているコードです:私はPythonのv.3.5を実行しています
from survey import AnonymousSurvey
# Define a question, and make a survey.
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
# Show the question, and store responses to the 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)
が。 2
必要と思われるその他の詳細がある場合は、それらを提供していただきます。
は、 'self 'を介して' question'を参照する必要があります。つまり、 'print(self.question)'を使用する必要があります。 –