我試圖通過創建一個類並在另一個文件中創建一個實例來創建一個簡單的調查。我的問題是,我收到一個錯誤,說我的'問題'變量沒有定義,當我在我的程序開始時明確定義它。這裏的錯誤:獲取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)
這裏還有我一起工作的代碼:
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)
我正在蟒蛇v.3.5。 2
如果您還有其他需要的細節,我會很樂意爲您提供。
應該通過'self'引用'question',即使用'print(self.question)'。 –