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

运行Python代码出现AttributeError:Student对象无_Student__marks属性

解决AttributeError: 'Student' object has no attribute '_Student__marks'错误

错误原因

创建Student实例时,仅触发了父类Info的__init__方法,但__marks属性是定义在Student类的data1方法中的,而你并没有调用data1,导致实例s不存在__marks属性,从而抛出错误。

修复方案

方案一:将data1改为__init__方法

让Student实例创建时自动初始化__marks,这是最符合Python类初始化规范的做法:

class Info:
  def __init__(self,name,Id,mobile):
    self.name=name
    self.Id=Id
    self.mobile=mobile

class Student(Info):
  def __init__(self,name, Id, mobile):
    super().__init__(name, Id, mobile)
    self.__marks={'Math': 140,'Software':130, 'Physics':90}

  def get_grades(self,courses):
    if courses in self.__marks:
      return self.__marks[courses]
    else:
      print('not available')

class Proffessor(Info):
  def data2(self,name, Id, mobile,salary):
    super().__init__(name, Id, mobile)
    self.__salary=salary

    s=Student('Ali', 77, 345678)
    print(s.get_grades(courses='Math'))

方案二:手动调用data1初始化属性

如果必须保留data1方法,创建Student实例后需要手动调用它来生成__marks:

class Info:
  def __init__(self,name,Id,mobile):
    self.name=name
    self.Id=Id
    self.mobile=mobile

class Student(Info):
  def data1(self,name, Id, mobile):
    super().__init__(name, Id, mobile)
    self.__marks={'Math': 140,'Software':130, 'Physics':90}

  def get_grades(self,courses):
    if courses in self.__marks:
      return self.__marks[courses]
    else:
      print('not available')

class Proffessor(Info):
  def data2(self,name, Id, mobile,salary):
    self.__salary=salary
    super().__init__(name, Id, mobile)

    s=Student('Ali', 77, 345678)
    s.data1('Ali', 77, 345678)  # 手动调用data1初始化__marks
    print(s.get_grades(courses='Math'))

额外优化建议

Proffessor类的data2方法中,建议先调用super().__init__完成父类属性初始化,再设置自身的__salary属性,这是子类初始化的常规顺序。

内容的提问来源于stack exchange,提问作者user21408341

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:45:17