我的Student类的add_student方法为何提示需额外参数,它仅需1个参数?
问题成因
- 你调用方法的方式错误:
add_student是类的普通实例方法,要求第一个参数必须是类的实例对象(对应方法定义里的self),你直接通过类名Student.add_student(student1)调用时,没有传入self对应的实参,解释器会判定你只传了1个参数,方法要求2个参数(self+student_object),所以抛出参数数量不匹配的错误。 - 存储逻辑设计错误:你把
student_list定义在__init__方法中,属于实例属性,每创建一个Student实例就会生成一个独立的空列表,无法实现全局统一存储所有学生的需求,就算调用方式改对了,数据也会分散在各个实例的私有列表中,无法统一管理。
修复方案
推荐将学生列表改为类属性,add_student改为类方法,所有实例共享同一个学生列表,符合全局存储学生的需求,修正后代码如下:
class Student: # 类属性:所有实例共享同一个学生列表 student_list =[] def __init__(self, first_name, last_name, student_num, email, pps, middle_name): self.first_name = first_name self.last_name = last_name self.student_num = student_num self.email = email self.__pps = pps self.__middle_name = middle_name def get_full_details(self): details = self.first_name + " " + self.last_name + " " + str(self.student_num) + " " + self.email return details @classmethod def add_student(cls, student_object): return cls.student_list.append(student_object) # 创建4个学生对象 student1 = Student("Jimmy", "Mccarthy", 1234, "johnmc@gmail.com", 8074454, "Edward") student2 = Student("James", "Flynn", 5678, "James@gmail.com", 7367736, "Borck") student3 = Student("Emma", "Mcgath", 9837, "EMChammer@hotmail.com", 3455433, "Richei") student4 = Student("Echo", "O Leary", 4334, "Echool@gmail.com", 4333357, "Wei") # 调用类方法添加学生 Student.add_student(student1) Student.add_student(student2) Student.add_student(student3) Student.add_student(student4) # 测试获取学生列表 print([stu.get_full_details() for stu in Student.student_list])
如果你坚持要用实例方法调用,也可以选择先实例化一个Student类的管理对象,再调用实例的add_student方法,但这种方式不如类属性的方式适合全局统一管理的场景:
# 仅示例不推荐的实现方式 manager = Student("","",0,"",0,"") manager.add_student(student1) print([stu.get_full_details() for stu in manager.student_list])
内容的提问来源于stack exchange,提问作者Andrewoca
相关产品推荐
相关产品推荐

