2017-08-05 112 views
0

我試圖更好地理解繼承。在下面的代碼中,當我嘗試打印friend.salary時,它會拋出一個AttributeErrorWorkingStudent是不是繼承了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 
+3

您的縮進是否正確?那'anna = WorkingStudent(...)'線真的應該在'__init__'裏面嗎? – BrenBarn

+0

是的,它的縮進效果很好。我認爲這是正確的縮進。 – learner

+0

[Python派生類和基類屬性?]的可能重複?(https://stackoverflow.com/questions/6396452/python-derived-class-and-base-class-attributes) –

回答

0

你應該修改源代碼如下

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(WorkingStudent,self).__init__(name,school) 
     self.salary = salary 
     # anna = WorkingStudent("Anna","SXS",25000) 
    def friend(self,friend_name): 
     return WorkingStudent(friend_name, self.school, self.salary) 

# You should put your code here, because as your original code 
# anna is an instance of Student not WorkingStudent class 
# so it and its friend don't have "salary". 
anna = WorkingStudent("Anna","SXS",25000) # After this line, anna is a different variable to "anna" variable that was defined before (anna = Student("Anna","MIT")) 
friend = anna.friend("Greg") # friend now is an instance of WorkingStudent class, so it have salary 
anna.marks.append(50) 
print(friend.salary) 

Editted。所以代碼現在可以工作

+0

請在回答之前測試您的代碼,它甚至不會運行 - 它不會糾正對「超級」的錯誤調用。但無論如何,改變安娜的班級並沒有什麼區別,因爲Motilal仍然會被創建爲「學生」,而不是「工作學生」,因此不會有「薪水」屬性。 –

+0

它運行起來,但對於在職學生的朋友應該是在職學生,並且對非在職學生的朋友是非在職學生是沒有意義的。以這種方式創建新學生是個壞主意,請參閱我對這個問題的評論。 –

+0

其實,我提出了一個解決方案,幫助@Harish Rao Balaji瞭解Python的繼承。我可以肯定的是,按照你的想法,以這種方式創建新的學生並不是一個好主意。這取決於每種情況。我明白,Harish Rao Balaji想創建一個學生,然後創建該學生的所有朋友,這裏的目的不是創造新學生,而是創造該學生的新朋友。我知道你可以創建新的學生,然後你定義另一個功能,使兩個學生成爲朋友。但是,這取決於Harish Rao Balaji的工作。 – Toandd