NameError引用实例方法中的变量

时间:2017-04-15 17:17:11

标签: python

我正在从“Crash Course in Python”一书中学习Python(使用v3.6)。在上一章中,我遇到了这个例子,但是当我运行它时,它会抛出一个错误。请告诉我我做错了什么。我无法弄清楚。 注意:两个程序都在同一个文件夹中。

**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

1 个答案:

答案 0 :(得分:1)

您想要打印self.question,而不是question。通常,在访问类中的实例变量时,需要显式使用self