新聞中心
封裝的目的是,保護隱私,把不想讓別人知道的東西封裝起來。下面通過例子來理解封裝

為象州等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及象州網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站制作、做網(wǎng)站、象州網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
定義了Student類及實例化,每個實例都擁有各自的name和score?,F(xiàn)在若需要打印一個學(xué)生的成績,可定義函數(shù) print_score(),該函數(shù)為類外的函數(shù)。
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): # 外部函數(shù)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優(yōu)化寫法
print_score(May)
print_score(Peter)既然Student實例本身就擁有這些數(shù)據(jù),要訪問這些數(shù)據(jù),就沒有必要從外面的函數(shù)去訪問,我們可以直接在Student類的內(nèi)部定義訪問數(shù)據(jù)的函數(shù)。這樣,就把數(shù)據(jù)給“封裝”起來了。
“封裝”就是將抽象得到的數(shù)據(jù)和行為(或功能)相結(jié)合,形成一個有機的整體(即類);封裝的目的是增強安全性和簡化編程,使用者不必了解具體的實現(xiàn)細節(jié),而只是要通過外部接口,一特定的訪問權(quán)限來使用類的成員。
而這些封裝數(shù)據(jù)的函數(shù)是和Student類本身是關(guān)聯(lián)起來的,我們稱之為類的方法。那如何定義類的方法呢?
就要用到對象 self 本身,參考上例,把 print_score() 函數(shù)寫為類的方法(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優(yōu)化寫法
May = Student("May",90)
Peter = Student("Peter",85)定義類的方法:除了第一個參數(shù)是self外,其他和普通函數(shù)一樣。
實例調(diào)用方法:只需要在實例變量上直接調(diào)用,除了self不用傳遞,其他參數(shù)正常傳入;注意,若類的方法僅需要self,不需要其他,調(diào)用該方法時,僅需instance_name.function_name()
這樣一來,我們從外部看Student類,就只需要知道,創(chuàng)建實例需要給出name和score,而如何打印,都是在Student類的內(nèi)部定義的,這些數(shù)據(jù)和邏輯被“封裝”起來了,調(diào)用很容易,但卻不用知道內(nèi)部實現(xiàn)的細節(jié)。
封裝的另一個好處是可以給Student類增加新的方法;這邊的方法也可以要求傳參,如新增定義compare 函數(shù),如下:
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優(yōu)化寫法
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) 文章標題:創(chuàng)新互聯(lián)Python教程:python是如何實現(xiàn)封裝的
分享鏈接:http://fisionsoft.com.cn/article/cdgeepj.html


咨詢
建站咨詢
