Skip to main content
 首页 » 编程设计

python之NameError 引用实例方法中的变量

2025年02月15日7bhlsheji

我正在从“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 

请您参考如下方法:

您想打印self.question,而不是question。一般情况下,访问类内的实例变量时,需要显式使用self。