马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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
现在,你应该能够正确地运行代码并存储用户的回答了。希望能对你有所帮助!
|