Python 類的封裝
阿新 • • 發佈:2019-01-03
類的封裝和構造可以讓我們更好的組織專案結構。
本章我們來學習類的封裝。
Student類的定義及例項化,每個例項都擁有各自的name和score。現在若需要列印一個學生的成績,可定義函式 print_score()
該函式為類外的函式,如下:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
May = Student("May",90) # 須要提供兩個屬性
Peter = Student("Peter" ,85)
print(May.name, May.score)
print(Peter.name, Peter.score)
def print_score(Student): # 外部函式
print_score(Student)
# print("%s's score is: %d" %(Student.name,Student.score))
# 普通 print 寫法
print("{0}'s score is: {1}".format(Student.name,Student.score)) # 建議使用 Python 2.7 + .format優化寫法
print_score(May)
print_score(Peter)
既然Student例項本身就擁有這些資料,要訪問這些資料,就沒有必要從外面的函式去訪問,我們可以直接在Student類的內部定義訪問資料的函式。這樣,就把資料給“封裝”起來了。
“封裝”就是將抽象得到的資料和行為(或功能)相結合,形成一個有機的整體(即類);封裝的目的是增強安全性和簡化程式設計,使用者不必瞭解具體的實現細節,而只是要通過外部介面,一特定的訪問許可權來使用類的成員。
而這些封裝資料的函式是和Student類本身是關聯起來的,我們稱之為類的方法。那如何定義類的方法呢?
就要用到物件 self 本身,參考上例,把 print_score() 函式寫為類的方法(Python2.7之後的版本,推薦.format 輸出寫法):
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print("{self.name}'s score is: {self.score}".format(self=self)) # Python 2.7 + .format優化寫法
May = Student("May",90)
Peter = Student("Peter",85)
定義類的方法:除了第一個引數是self外,其他和普通函式一樣。
例項呼叫方法:只需要在例項變數上直接呼叫,除了self不用傳遞,其他引數正常傳入;注意,若類的方法僅需要self,不需要其他,呼叫該方法時,僅需 instance_name.function_name()
這樣一來,我們從外部看Student類,就只需要知道,建立例項需要給出name和score,而如何列印,都是在Student類的內部定義的,這些資料和邏輯被“封裝”起來了,呼叫很容易,但卻不用知道內部實現的細節。
封裝的另一個好處是可以給Student類增加新的方法;這邊的方法也可以要求傳參,如新增定義compare 函式,如下:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print("{self.name}'s score is: {self.score}".format(self=self)) # Python 2.7 + .format優化寫法
def compare(self,s):
if self.score>s:
print("better than %d" %(s))
elif self.score==s:
print("equal %d" %(s))
else:
print("lower than %d" %(s))
May = Student("May",90)
Peter = Student("Peter",85)
May.print_score()
Peter.print_score()
May.compare(100)
May.compare(90)
May.compare(89)