Python Forum

Full Version: Getting Attribute Error In My Code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
this is my output before it breaks

tired from a long day of work
Margot



This is my error

Error:
Traceback (most recent call last): File "C:\Users\gabri\AppData\Local\Programs\Python\Python36\First Program.py", line 39, in <module> print(Margot.toString()) File "C:\Users\gabri\AppData\Local\Programs\Python\Python36\First Program.py", line 34, in toString return 'Hello I am {}, I am {} years old, my favorite class is {}, and today I feel {}.'.format(self.__name, self.__age, self.__fav_class, self.__feels) AttributeError: 'Student' object has no attribute '_Student__name' [hr]
class Human:#Parent Class
__name = None
__age = None
__feels = None
def __init__(self, name, age, feels):#when creating a new human ur parameters pass through __init__
self.__name = name
self.__age = age
self.__feels = feels
def set_name(self, name):#setters
self.__name = name
def set_age(self, age):
self.__age = age
def set_feels(self, feels):
self.__feels = feels
def get_name(self):#getters
return self.__name
def get_age(self):
return self.__age
def get_feels(self):
return self.__feels
def toString(self):
return 'Hello I am {}, I am {} years old, and today I feel {}.'.format(self.__name, self.__age, self.__feels)#just another way of formatting text

class Student(Human):#subclass/inherented class/child class
__fav_class = None
def __init__(self, name, age, feels, fav_class):#by default has all functions of its Parent class however you can overide them by redefining them
self.__fav_class = fav_class
super(Student, self).__init__(name, age, feels)#runs name age and feels through Human.__init__
def set_fav_class(self, fav_class):
self.__fav_class = fav_class
def get_fav_class(self):
return self.__fav_class
def toString(self):
return 'Hello I am {}, I am {} years old, my favorite class is {}, and today I feel {}.'.format(self.__name, self.__age, self.__fav_class, self.__feels)
Bob = Human('Bob', 32, 'tired from a long day of work')
print(Bob.get_feels())
Margot = Student('Margot', 15, 'happy', 'Chem')
print(Margot.get_name())
print(Margot.toString())
The error is in the Student class
def toString(self):
return 'Hello I am {}, I am {} years old, my favorite class is {}, and today I feel {}.'.format(self.__name, self.__age, self.__fav_class, self.__feels)
You cannot directly call members (self.__name, self.__age, self.__feels) from parent class (Human)... if that was your intentions. They must be passed using those getters methods you created in the Human class.