运行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
相关产品推荐
相关产品推荐

