pyhton 总提示 name 'XXX' is not defined 的解决办法

pyhton 总提示 name ‘XXX’ is not defined 的解决办法

language_survey.py

#-*-coding:GBK -*- 
#11.5

from survey import AnonymousSurvey 
#定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = "What language did you first learn to speak?" 
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) 
# 显示调查结果
print("\nThank you to everyone who participated in the survey!") 
my_survey.show_results()

调用的survey

#-*-coding:GBK -*- 
#11.4
class AnonymousSurvey():
	"""收集匿名调查问卷的答案"""
	def __init__(self,question):
		"""存储一个问题,并为存储答案做准备""" 
		self.question=question
		self.responses=[]
	
	def show_question(self):
		"""显示调查问卷""" 
		print(question)	
	
	def store_response(self,new_response):
		"""存储单份调查答卷""" 
		self.responses.append(new_response)
		
	def show_results(self):
		"""显示收集到的所有答卷""" 
		print("Survey results:")
		for response in responses:
			print('- '+ response)

如果把language_survey.py的代码放入survey.py中,提示
name ‘responses’ is not defined

首先以为是代码中间有空格,找了两天,结果不时,不定时在哪个文件中出错,
总是提示
name ‘responses’ is not defined
name ‘question’ is not defined

后来经过网上询问,结果是这里出的问题:

    def show_question(self):
            """显示调查问卷""" 
            print(question)          -- self.question

    def show_results(self):
            """显示收集到的所有答卷""" 
            print("Survey results:")
            for response in responses:   -- self.responses
                    print('- '+ response)

在定义class中,需要用self声明的,下面用到的,一定要带self.

希望大家不要犯同样的错误。

你可能感兴趣的:(python学习)