Search code examples
pythonoopprivate-members

AttributeError: 'Student' object has no attribute '_Student__marks'


gives me this error when I run this code

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'))

I tried to print the name of the course alone and also didn't work


Solution

  • You need to replace

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

    with

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

    so that python recognizes the method as a constructor, and not a class method. That way, when you reference self.__marks in get_grades it will be initialized. That is, the constructor will run as soon as you create the student object, whereas data1 won't run unless you call it. Because data1 doesn't run, the self.__marks variable is never initialized.