You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python OOP入门调用类方法报AttributeError错误求解

问题排查与修正

报错直接原因

你收到的AttributeError: 'list' object has no attribute 'totalAverageMark'错误,核心原因是:getName、totalAverageMark是你定义在Student类下的成员方法,仅能由Student类的实例调用。而你代码中的students是存储多个Student实例的Python列表对象,列表本身不存在这两个自定义方法,因此触发属性错误。

代码其他逻辑问题

  • 计算逻辑错误:totalAverageMark方法中累加的是self.averageMark,也就是当前调用该方法的单个实例的分数,即使循环遍历传入的列表,最终累加的都是同一个值,无法得到所有实例的分数总和
  • 传参不匹配:两个自定义方法都声明了需要传入入参,但你调用时没有传递对应参数,就算用Student实例调用也会触发参数缺失错误
  • getName逻辑无效:方法内部遍历传入的列表后直接返回当前实例的姓氏,永远只会返回单个值,无法实现遍历输出所有实例姓氏的需求

修正后参考实现

class Student:
    # 类属性:统计实例总数、存储所有已创建的实例
    anz = 0
    all_students = []

    def __init__(self, vorname, nachname, studentId, averageMark):
        self.vorname = vorname
        self.nachname = nachname
        self.studentId = studentId
        self.averageMark = averageMark
        # 实例创建时更新类属性
        Student.anz += 1
        Student.all_students.append(self)

    # 类方法:直接通过类调用,统计所有实例的平均分
    @classmethod
    def totalAverageMark(cls):
        summe = 0
        for s in cls.all_students:
            summe += s.averageMark
        return summe / cls.anz

    # 实例方法:返回当前实例的全名
    def getFullName(self):
        return f"{self.vorname} {self.nachname}"

# 创建学生实例,无需额外维护外部列表
Student("Maxine", "Muster", 2, 1.0)
Student("Bert", "Beispiel", 1, 2.0)

# 调用类方法获取所有学生的平均分
print(Student.totalAverageMark())
# 遍历所有实例输出姓名
for s in Student.all_students:
    print(s.getFullName())

内容的提问来源于stack exchange,提问作者Martin Müller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:36:08