'How inheritance affect the subclass [duplicate]
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?
Solution 1:[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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marc Steven |
