我正在尝试通过创建一个类并在另一个文件中创建它的实例来创建一个简单的调查。我的问题是,当我在程序开始时明确定义它时,我收到一条错误,指出我的'question'变量没有定义。这是错误:
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)
我正在运行python v.3.5.2
如果您认为还需要其他详细信息,我将很乐意为您提供。
答案 0 :(得分:2)
在那个功能中。 question
未定义。但是,你有self.question
。 question
是__init__
函数的本地。
答案 1 :(得分:0)
def show_question(self):
"""Show the survey question."""
print(self.question)
在Python中,您必须使用self
访问类实例属性。