python问题
class AnonymousSurvey():def __init__(self,question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self,new_responsse):
self.responses.append(new_response)
def show_results(self):
print('Survey results:')
for response in self.responses:
print('- '+response)
from survey import 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()
What language did you first learn to speak?
Enter 'q' at any time to quit.
Language:w
Traceback (most recent call last):
File "D:/python文件/学习/十一、测试代码/11.2kh/11.2kh.py", line 12, in <module>
my_survey.store_response(response)
File "D:/python文件/学习/十一、测试代码/11.2kh\survey.py", line 10, in store_response
self.responses.append(new_response)
NameError: name 'new_response' is not defined
>>>
这个问题,是不是我类的方法建的有问题啊,求教 是的,你的类方法 store_response 中有一个拼写错误。在方法参数中,你使用了 new_responsse 而不是 new_response 。因此,在方法体中,Python无法找到名为 new_response 的变量,从而导致了 NameError 错误。
要解决这个问题,你只需将 new_responsse 改为 new_response 即可。修改后的代码如下:
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print('Survey results:')
for response in self.responses:
print('- ' + response)
请注意,你还需要在代码的开头导入 AnonymousSurvey 类:
from survey import AnonymousSurvey
现在,你应该能够正确地运行代码并存储用户的回答了。希望能对你有所帮助! 问题分析:
这个错误提示是说new_response未定义,但是我们看代码,确实定义了response变量,没有定义new_response变量,因此会有这个错误。
解决方案:
将store_response函数的参数名改为new_response即可。修改后的代码如下:
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print('Survey results:')
for response in self.responses:
print('- ' + response)
在主程序中,也需要将my_survey.store_response(response)改为my_survey.store_response(new_response)。
完整代码如下:
from survey import 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:
new_response = input('Language:')
if new_response == 'q':
break
my_survey.store_response(new_response)
print('\nThank you to everyone who participated in the survey!')
my_survey.show_results()
希望对你有所帮助。
球一个最佳答案谢谢啦!这对我非常重要!{:10_254:}{:10_254:}{:10_254:}
页:
[1]