Python类方法调用报错:store_response()需1个位置参数却传入2个
问题分析与解决
你的代码存在几个关键问题,其中一个直接引发了当前报错,其余会导致后续运行异常:
1. 实例方法参数缺失(直接触发当前报错)
虽然你贴出的store_response方法包含self参数,但从报错信息判断,你实际运行的代码里该方法大概率没有定义self。类的所有实例方法必须把self作为第一个参数(名称可自定义,但self是通用约定)——调用my_survey.store_response(response)时,Python会自动把实例my_survey作为第一个参数传入方法,若没写self,方法会收到两个参数(实例本身+你传入的response),但方法定义只接受1个,于是触发报错。
2. 属性名拼写不一致
在类的__init__方法里,你定义的响应列表是self.response = [],但在store_response和show_results方法里却用了self.responses(多了一个s)。这会导致后续运行时出现AttributeError,提示找不到responses属性。建议统一为复数形式self.responses = [],更符合语义。
3. 缺少类实例化代码
你的主代码直接调用my_survey.show_question(),但没有创建AnonymousSurvey的实例,会导致my_survey未定义报错,需要补充实例化语句。
修正后的完整代码
# Consider a class that helps administer anonymous surveys class AnonymousSurvey: """Collects anonymous answers to survey questions""" 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(self.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 self.responses: print(f" -{response}")
# I want the survey to run for about a minute import time # 新增类实例化代码 my_survey = AnonymousSurvey("What's your favorite programming language?") my_survey.show_question() counter = 0 time_duration = 60 start_time = time.time() while time.time() < start_time + time_duration: counter += 1 response = input("Language: ") my_survey.store_response(response) # Show the results of your survey print("\nThank you to everyone who participated in the survey.") my_survey.show_results()
内容的提问来源于stack exchange,提问作者Angel Arce Q
相关产品推荐
相关产品推荐

