承接上一節(jié),學(xué)了Student類的定義及實(shí)例化,每個(gè)實(shí)例都擁有各自的name和score。現(xiàn)在若需要打印一個(gè)學(xué)生的成績(jī),可定義函數(shù) PRint_score()
該函數(shù)為類外的函數(shù),如下:
1 class Student(object): 2 def __init__(self, name, score): 3 self.name = name 4 self.score = score 5 6 May = Student("May",90) # 須要提供兩個(gè)屬性 7 Peter = Student("Peter",85) 8 print(May.name, May.score) 9 print(Peter.name, Peter.score)10 11 def print_score(Student): # 外部函數(shù)print_score(Student)12 # print("%s's score is: %d" %(Student.name,Student.score)) # 普通 print 寫法13 print("{0}'s score is: {1}".format(Student.name,Student.score)) # 建議使用 Python 2.7 + .format優(yōu)化寫法14 print_score(May) 15 print_score(Peter)
既然Student實(shí)例本身就擁有這些數(shù)據(jù),要訪問這些數(shù)據(jù),就沒有必要從外面的函數(shù)去訪問,我們可以直接在Student類的內(nèi)部定義訪問數(shù)據(jù)的函數(shù)。這樣,就把數(shù)據(jù)給“封裝”起來了。
“封裝”就是將抽象得到的數(shù)據(jù)和行為(或功能)相結(jié)合,形成一個(gè)有機(jī)的整體(即類);封裝的目的是增強(qiáng)安全性和簡(jiǎn)化編程,使用者不必了解具體的實(shí)現(xiàn)細(xì)節(jié),而只是要通過外部接口,一特定的訪問權(quán)限來使用類的成員。
而這些封裝數(shù)據(jù)的函數(shù)是和Student類本身是關(guān)聯(lián)起來的,我們稱之為類的方法。那如何定義類的方法呢?
就要用到對(duì)象 self 本身,參考上例,把 print_score() 函數(shù)寫為類的方法(Python2.7之后的版本,推薦.format 輸出寫法):
1 class Student(object): 2 def __init__(self, name, score): 3 self.name = name 4 self.score = score 5 6 def print_score(self): 7 print("{self.name}'s score is: {self.score}".format(self=self)) # Python 2.7 + .format優(yōu)化寫法 8 9 May = Student("May",90) 10 Peter = Student("Peter",85)
定義類的方法:除了第一個(gè)參數(shù)是self外,其他和普通函數(shù)一樣。
實(shí)例調(diào)用方法:只需要在實(shí)例變量上直接調(diào)用,除了self不用傳遞,其他參數(shù)正常傳入;注意,若類的方法僅需要self,不需要其他,調(diào)用該方法時(shí),僅需 instance_name.function_name()
這樣一來,我們從外部看Student類,就只需要知道,創(chuàng)建實(shí)例需要給出name和score,而如何打印,都是在Student類的內(nèi)部定義的,這些數(shù)據(jù)和邏輯被“封裝”起來了,調(diào)用很容易,但卻不用知道內(nèi)部實(shí)現(xiàn)的細(xì)節(jié)。
封裝的另一個(gè)好處是可以給Student類增加新的方法;這邊的方法也可以要求傳參,如新增定義compare 函數(shù),如下:
1 class Student(object): 2 def __init__(self, name, score): 3 self.name = name 4 self.score = score 5 6 def print_score(self): 7 print("{self.name}'s score is: {self.score}".format(self=self)) # Python 2.7 + .format優(yōu)化寫法 8 9 def compare(self,s):10 if self.score>s:11 print("better than %d" %(s))12 elif self.score==s:13 print("equal %d" %(s))14 else:15 print("lower than %d" %(s))16 17 May = Student("May",90) 18 Peter = Student("Peter",85) 19 20 May.print_score()21 Peter.print_score()22 23 May.compare(100)24 May.compare(90)25 May.compare(89)
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注