AttributeError: 'Student' 对象没有属性 '_Student__marks'

问题描述 投票:0回答:2

运行此代码时出现此错误

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)
    #print(s.get_grades('Math'))
    print(s.get_grades(courses='Math'))

我试过单独打印课程名称也没用

python oop private-members
2个回答
1
投票

你需要更换

def data1(self,name, Id, mobile):

def __init__(self,name, Id, mobile):

以便 python 将该方法识别为构造函数,而不是类方法。这样,当您在

self.__marks
中引用
get_grades
时,它将被初始化。也就是说,构造函数将在您创建学生对象后立即运行,而
data1
除非您调用它,否则不会运行。因为
data1
没有运行,所以
self.__marks
变量永远不会被初始化。


1
投票

错误

AttributeError: 'Student' object has no attribute '_Student__marks'
的发生是因为 Student 类中的
__marks
属性被定义为具有名称修饰的私有属性。这意味着属性名称以
_Student
为前缀以使其私有。

在您的代码中,当您尝试在

self.__marks
方法中访问
get_grades
时,它正在寻找
_Student__marks
而不是
__marks
。但是,
__marks
属性无法从类外部直接访问,从而导致 AttributeError。

要解决此问题,您可以将 __marks 属性公开或在 Student 类中提供一个公共方法来访问 __marks 属性。

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, course):
        if course in self.marks:
            return self.marks[course]
        else:
            print('Grades not available for the course:', course)

通过此修改,您可以使用

s.marks
而不是
s._Student__marks
访问标记属性。

© www.soinside.com 2019 - 2024. All rights reserved.