-1

I've been doing some Python assignment and encountered something I couldn't explain:

class Person:
    def __init__(self, name='Shooki', age=20):
        self.__name = name
        self.__age = age

class Student(Person):

    def __init__(self, name, age, grade_avg=80):
        super(Student, self).__init__(name, age)
        self.__grade_avg = grade_avg

    def get_grade_avg(self):
        return self.__grade_avg

    def set_grade_avg(self, new_grade_avg):
        self.__grade_avg = new_grade_avg

    def __str__(self):
        return "Student {} is {} years old and his average grade is {}".\
            format(self.get_name(), self.get_age(), self.__grade_avg)

When I tried to write

def __str__(self):
    return "Student {} is {} years old and his average grade is {}".\
        format(self.__name, self.__age, self.__grade_avg)

it raised an error

File "C:/Networks/Work/Scripts/network.py", line 39, in __str__
 format(self.__name, self.__age, self.__grade_avg) AttributeError: 'Student' object has no attribute '_Student__name'

someone could explain the logic behind it?

azro
  • 53,056
  • 7
  • 34
  • 70
  • Don't use double underscore for attribute name, maybe only for some method that you want to hide – azro Mar 13 '22 at 09:13

1 Answers1

-1

nheritance allows us to define a class that inherits all the methods and properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Please read here to know more about it.inheritance

The error as below:

  super(Student, self).__init__(name, age)

it should be

  super().__init__(name, age)
Marc Steven
  • 477
  • 4
  • 16
  • That isn't the reason. Even second option is effectivly recommended now, both are same – azro Mar 13 '22 at 09:13