我試圖更好地理解繼承。在下面的代碼中,當我嘗試打印friend.salary
時,它會拋出一個AttributeError
。 WorkingStudent
是不是繼承了Student
類的所有方法?瞭解繼承
class Student:
def __init__(self,name,school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks)/len(self.marks)
def friend(self,friend_name):
return Student(friend_name, self.school)
anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)
class WorkingStudent(Student):
def __init__(self,name,school,salary):
super().__init__(self,name,school)
self.salary = salary
anna = WorkingStudent("Anna","SXS",25000)
anna.friend("Greg")
anna.marks.append(50)
print friend.salary
您的縮進是否正確?那'anna = WorkingStudent(...)'線真的應該在'__init__'裏面嗎? – BrenBarn
是的,它的縮進效果很好。我認爲這是正確的縮進。 – learner
[Python派生類和基類屬性?]的可能重複?(https://stackoverflow.com/questions/6396452/python-derived-class-and-base-class-attributes) –