Python學習(七)面向對象 ——封裝


Python 類的封裝

 

  承接上一節,學了Student類的定義及實例化,每個實例都擁有各自的name和score。現在若需要打印一個學生的成績,可定義函數 print_score()

  該函數為類外的函數,如下:

 1 class Student(object):
 2     def __init__(self, name, score):
 3         self.name = name
 4         self.score = score
 5 
 6 May = Student("May",90)                      # 須要提供兩個屬性
 7 Peter = Student("Peter",85)
 8 print(May.name, May.score)
 9 print(Peter.name, Peter.score)
10 
11 def print_score(Student):                    # 外部函數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優化寫法
14 print_score(May)    
15 print_score(Peter)

 

  既然Student實例本身就擁有這些數據,要訪問這些數據,就沒有必要從外面的函數去訪問,我們可以直接在Student類的內部定義訪問數據的函數。這樣,就把數據給“封裝”起來了。

  “封裝”就是將抽象得到的數據和行為(或功能)相結合,形成一個有機的整體(即類);封裝的目的是增強安全性和簡化編程,使用者不必了解具體的實現細節,而只是要通過外部接口,一特定的訪問權限來使用類的成員。

  而這些封裝數據的函數是和Student類本身是關聯起來的,我們稱之為類的方法。那如何定義類的方法呢?

  就要用到對象 self 本身,參考上例,把 print_score() 函數寫為類的方法(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優化寫法
 8         
 9 May = Student("May",90)        
10 Peter = Student("Peter",85)        

 

  定義類的方法:除了第一個參數是self外,其他和普通函數一樣。

  實例調用方法:只需要在實例變量上直接調用,除了self不用傳遞,其他參數正常傳入;注意,若類的方法僅需要self,不需要其他,調用該方法時,僅需 instance_name.function_name()

  這樣一來,我們從外部看Student類,就只需要知道,創建實例需要給出name和score,而如何打印,都是在Student類的內部定義的,這些數據和邏輯被“封裝”起來了,調用很容易,但卻不用知道內部實現的細節。

  封裝的另一個好處是可以給Student類增加新的方法;這邊的方法也可以要求傳參,如新增定義compare 函數,如下:

 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優化寫法
 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM