2017-04-01 60 views
-1

我寫了一個代碼,其中我有一個基類SchoolMember並派生出兩個類:Teacher & Student。請參考下面的代碼:繼承Python編程

class SchoolMember: 
    '''Represents school member''' 
    def __init__(self,name,age): 
     self.name=name 
     self.age=age 
     print('Initialised school member is:', format(self.name)) 

    def tell(self): 
     print ('Name: \t Age: ', format(self.name, self.age)) 

class Teacher(SchoolMember): 
    def __init__(self,name,salary,age): 
     SchoolMember.__init__(self,name,age) 
     self.salary=salary 
     print ('Initialised teacher is ', format(self.name)) 

    def tell(self): 
     '''Prints the salary of the teacher''' 
     print('Salary of teacher is ', format(self.salary)) 

class Student(SchoolMember): 
    def __init__(self,name,age,fees): 
     SchoolMember.__init__(self,name,age) 
     self.fees=fees 
     print('Initialised student is',format(self.name)) 

    def tell(self): 
     '''Tells the fees of the student''' 
     print('Fees of student is', format(self.fees)) 

t = Teacher('Richa', 26,4000) 
s = Student('Shubh',21, 2000) 

print() 
members = [t,s] 
for member in members: 
    member.tell() 

輸出:

('Initialised school member is:', 'Richa') 
('Initialised teacher is ', 'Richa') 
('Initialised school member is:', 'Shubh') 
('Initialised student is', 'Shubh') 
() 
('Salary of teacher is ', '4000') 
('Fees of student is', '2000') 

現在,我的問題是:如何讓輸出的年齡?

+0

我不清楚你在問什麼。你在問如何調用基本的tell類型或Martijn正在回答的格式問題,還是其他一些問題? – Foon

回答

1

您想了解format() function文檔;你沒有按照設計的方式使用它;該函數根據規範格式化一個值(可選的第二個參數)。

實際上,您根本不需要使用它,所有

使用str.format()相反,對字符串的方法:

print 'Name: {}\t Age: {}'.format(self.name, self.age) 

這裏{}佔位符代替你傳遞給方法的值。

請注意,我沒有使用print作爲函數;在Python 2中,它是陳述;這就是爲什麼你執行print()時看到();那真的只是print tuple()。你可能在你的模塊的頂部使用from __future__ import print_function,但我會堅持現在的陳述;最好是完全切換到Python 3。

接下來,你想直接從您的子類執行覆蓋SchoolMember.tell()方法:

def tell(self): 
    '''Tells the fees of the student''' 
    SchoolMember.tell(self) 
    print 'Fees of student is {}'.format(self.fees) 

因爲你訪問該方法綁定的類,你需要在self手動傳遞。在新的類中(繼承自object,Python 3中的默認基類),你也可以使用super() function;如果您的教程使用的是super()已經但您無法使其工作,您很可能遵循Python 3教程,並且想要升級,而不是堅持使用該語言的舊版本。