代码段一:
"""
Author: yeahthon
Date : 2019-08-09 12:28:47
E-mail: yeahthon@163.com
"""
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 result:")
for response in responses:
print('- ' + response)
代码段二:
"""
Author: yeahthon
Date : 2019-08-09 12:50:20
E-mail: yeahthon@163.com
"""
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("\nThink you to everyone cho participated in the survey!")
my_survey.show_results()
运行时显示异常:
G:\python\untitled1\venv\Scripts\python.exe G:/python/untitled1/language_survey.py
Traceback (most recent call last):
File "G:/python/untitled1/language_survey.py", line 13, in <module>
my_survey.show_question()
File "G:\python\untitled1\survey.py", line 16, in show_question
print(question)
NameError: name 'question' is not defined
Process finished with exit code 1
异常分析:名称question未被定义
异常处理:不能直接引用或者遍历形参, question在代码段一第9行已经定义为变量形参,引用输出时应当填入相应实参,即将代码段一第16行 question 改为 self.question,第25行 responses 改为 self.responses。