您好,登錄后才能下訂單哦!
這篇“Python私有函數(shù),私有變量及封裝的方法”文章的知識點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python私有函數(shù),私有變量及封裝的方法”文章吧。
私有函數(shù)與私有變量中的私有是什么意思? —> 簡單理解就是獨(dú)自擁有、不公開、不分享的意思。放到函數(shù)與變量中就是獨(dú)自擁有的函數(shù)與獨(dú)自擁有的變量,并且不公開。這樣我們就理解了什么是私有函數(shù)與私有變量。
無法被實例化后的對象調(diào)用的類中的函數(shù)與變量
雖然無法被實例化后的對象調(diào)用,但是在 類的內(nèi)部我們可以 調(diào)用私有函數(shù)與私有變量
私有函數(shù)與私有變量的目的:只希望類內(nèi)部的業(yè)務(wù)調(diào)用使用,不希望被實例化對象調(diào)用使用
既然有私有函數(shù)與私有變量,其實能被實例化對象調(diào)用的函數(shù)與變量就是公有函數(shù)與公有變量,不過一般我們都稱之為函數(shù)與變量。
如何定義私有函數(shù)與私有變量:在 類變量 與 類函數(shù) 前添加 __ (2個下橫線)即可定義私有函數(shù)與私有變量;變量或函數(shù)的后面無需添加,左右都有兩個下橫線,是 類的內(nèi)置函數(shù) 的定義規(guī)范。
私有函數(shù)與私有變量示例如下:
class Persion(object): def __init__(self): self.name = name self.__age = 18 # 'self.__age' 為 Persion類 私有變量 def run(self): print(self.name, self.__age) # 在 Persion類 的代碼塊中,私有變量依然可以被調(diào)用 def __eat(self): # '__eat(self)' 為 Persion類 私有函數(shù) return 'I want eat some fruits'
接下來我們根據(jù)上面的示例代碼做一下修改,更好的演示一下 私有函數(shù)與私有變量 方便加深理解
class PersionInfo(object): def __init__(self, name): self.name = name def eat(self): result = self.__eat() print(result) def __eat(self): return f'{self.name} 最喜歡吃水果是 \'榴蓮\' 和 \'番石榴\'' def run(self): result = self.__run() print(result) def __run(self): return f'{self.name} 最喜歡的健身方式是 \'跑步\' 和 \'游泳\'' persion = PersionInfo(name='Neo') persion.eat() persion.run() # >>> 執(zhí)行結(jié)果如下: # >>> Neo 最喜歡吃水果是 '榴蓮' 和 '番石榴' # >>> Neo 最喜歡的健身方式是 '跑步' 和 '游泳'
我們再試一下 通過 實例化對象 persion 調(diào)用 __eat 私有函數(shù)試試
class PersionInfo(object): def __init__(self, name): self.name = name def eat(self): result = self.__eat() print(result) def __eat(self): return f'{self.name} 最喜歡吃水果是 \'榴蓮\' 和 \'番石榴\'' def run(self): result = self.__run() print(result) def __run(self): return f'{self.name} 最喜歡的健身方式是 \'跑步\' 和 \'游泳\'' persion = PersionInfo(name='Neo') persion.__eat() # >>> 執(zhí)行結(jié)果如下: # >>> AttributeError: 'PersionInfo' object has no attribute '__eat' # >>> 再一次證明 實例化對象是不可以調(diào)用私有函數(shù)的
那么事實真的是 實例化對象就沒有辦法調(diào)用 私有函數(shù) 了么?其實不是的,我們繼續(xù)往下看
class PersionInfo(object): def __init__(self, name): self.name = name def eat(self): result = self.__eat() print(result) def __eat(self): return f'{self.name} 最喜歡吃水果是 \'榴蓮\' 和 \'番石榴\'' def run(self): result = self.__run() print(result) def __run(self): return f'{self.name} 最喜歡的健身方式是 \'跑步\' 和 \'游泳\'' persion = PersionInfo(name='Neo') # 通過 dir() 函數(shù) 查看一下 實例化對象 persion 中都有哪些函數(shù)? print(dir(persion))
可以看到 實例化對象 persion 也有兩個私有變量 _Persion__eat 和 _Persion__run ,嘗試直接用實例化對象 persion 調(diào)用私有變量。
class PersionInfo(object): def __init__(self, name): self.name = name def eat(self): result = self.__eat() print(result) def __eat(self): return f'{self.name} 最喜歡吃水果是 \'榴蓮\' 和 \'番石榴\'' def run(self): result = self.__run() print(result) def __run(self): return f'{self.name} 最喜歡的健身方式是 \'跑步\' 和 \'游泳\'' persion = PersionInfo(name='Neo') # 通過 dir() 函數(shù) 查看一下 實例化對象 persion 中都有哪些函數(shù)? print(dir(persion)) print(persion._PersionInfo__eat()) print(persion._PersionInfo__run()) # >>> 執(zhí)行結(jié)果如下圖:
可以看到通過這種方式,我們的 實例化對象 persion 也成功的調(diào)用了 PersionInfo 類 的私有函數(shù);但是既然是 私有函數(shù) ,那么目的就是不希望被實例化對象調(diào)用,所以我們還是按照編碼規(guī)范來使用比較好。
附:私有變量(私有屬性)的使用與私有函數(shù)一樣,我們看下面的示例
class PersionInfo(object): __car = 'BMW' def __init__(self, name, sex): self.name = name self.__sex = sex def info(self): result = self.__info() print(result) def __info(self): return f'{self.name} 性別:{self.__sex} ,他有一輛:\'{self.__car}\'' persion = PersionInfo(name='Neo', sex='男') persion.info() # >>> 執(zhí)行結(jié)果如下: # >>> Neo 性別:男 ,他有一輛:'BMW' # >>> 嘗試調(diào)用私有函數(shù) 私有函數(shù)與變量(屬性)['_PersionInfo_01__car', '_PersionInfo_01__info', '_PersionInfo_01__sex'] print(persion01._PersionInfo_01__info()) # >>> 執(zhí)行結(jié)果如下: # >>> Neo 性別:男 ,他有一輛:'BMW'
其實 Python 中并沒有 封裝 這個功能,而封裝只是針對 Python 中某種業(yè)務(wù)場景的一種概念而已。
封裝的概念 —> 將不對外的私有屬性或方法通過可以對外使用的函數(shù)而使用(類中定義的私有函數(shù)、私有方法只能在類的內(nèi)部使用,外部無法訪問),這樣做的主要原因是:保護(hù)隱私,明確的區(qū)分內(nèi)與外。
封裝的示例如下:
class Persion(object): def __hello(self, data): print('hello %s' % data) def helloworld(self): self.__hello('world') if __name__ == '__main__' persion = Persion() persion.helloworld() # >>> 執(zhí)行結(jié)果如下: # >>> hello world # >>> 我們可以看到 helloworld() 是基于 私有函數(shù) __hello() 來執(zhí)行的; # >>> 所以我們是通過對外的函數(shù) helloworld() 調(diào)用了內(nèi)部私有函數(shù) __hello ; 這就是 Python 中的 封裝的概念。
需求:
用類和對象實現(xiàn)銀行賬戶的資金交易管理,包括存款、取款和打印交易詳情,交易詳情中包含每次交易的時間、存款或者取款的金額、每次交易后的余額。
腳本示例如下:
#coding: utf-8 import time class MoneyExchange(object): money = 0 abstract = [] single_bill_list = [] bill_list =[] transcation_num = 0 currency_type = "人民幣" service_option_num = [] service_option = [] service_menu ={ 1: "1:存款", 2: "2:取款", 3: "3:查看明細(xì)", 4: "4:查看余額", 0: "0:退出系統(tǒng)" } for key, value in service_menu.items(): service_option_num.append(key) service_option.append(value) def welcome_menu(self): print('*' * 20 + '歡迎使用資金交易管理系統(tǒng)' + '*' * 20) for i in range(0,len(self.service_option)): print(self.service_option[i]) print('*' * 60) def save_money(self): self.money_to_be_save = float(input('請輸入存錢金額:')) self.abstract = '轉(zhuǎn)入' self.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.money += self.money_to_be_save self.single_bill_list.append(self.time) self.single_bill_list.append(self.abstract) self.single_bill_list.append(self.money_to_be_save) self.single_bill_list.append(self.currency_type) self.single_bill_list.append(self.money) self.bill_list.append(self.single_bill_list) self.single_bill_list = [] self.transcation_num += 1 print('已成功存入!當(dāng)前余額為:%s 元' % self.money) input('請點(diǎn)擊任意鍵以繼續(xù)...') def withdraw_money(self): self.money_to_be_withdraw = float(input('請輸入取出金額:')) if self.money_to_be_withdraw <= self.money: self.abstract = '取出' self.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.money -= self.money_to_be_withdraw self.single_bill_list.append(self.time) self.single_bill_list.append(self.abstract) self.single_bill_list.append(self.money_to_be_withdraw) self.single_bill_list.append(self.currency_type) self.single_bill_list.append(self.money) self.bill_list.append(self.single_bill_list) self.single_bill_list = [] self.transcation_num += 1 print('已成功取出!當(dāng)前余額為:%s 元' % self.money) input('請點(diǎn)擊任意鍵以繼續(xù)...') else: print('您輸入的取出金額超過余額,無法操作!請重新輸入') input('請點(diǎn)擊任意鍵以繼續(xù)...') def check_bill_list(self): print('| 交易日期 | 摘要 | 金額 | 幣種 | 余額 |') for i in range(0, self.transcation_num): print("|%s | %s | %s | %s | %s|" % ( self.bill_list[i][0], self.bill_list[i][1], self.bill_list[i][2], self.bill_list[i][3], self.bill_list[i][4] )) input('請點(diǎn)擊任意鍵以繼續(xù)...') def check_money(self): print('賬戶余額為:%s元' % self.money) input('請點(diǎn)擊任意鍵以繼續(xù)...') def user_input(self): option = float(input('請輸入選項:')) if option in self.service_option_num: if option == 1: self.save_money() if option == 2: self.withdraw_money() if option == 3: self.check_bill_list() if option == 4: self.check_money() if option == 0: print('您已成功退出,謝謝!') exit() else: print('抱歉,你輸入有誤,請重新輸入!') input('請點(diǎn)擊任意鍵以繼續(xù)...') money_exchange = MoneyExchange() while True: money_exchange.welcome_menu() money_exchange.user_input() # >>> 執(zhí)行結(jié)果如下: # >>> ********************歡迎使用資金交易管理系統(tǒng)******************** # >>> 1:申請存款 # >>> 2:申請取款 # >>> 3:查看明細(xì) # >>> 4:查看余額 # >>> 0:退出系統(tǒng) # >>> ************************************************************ # >>> 根據(jù)提示執(zhí)行對應(yīng)的操作
以上就是關(guān)于“Python私有函數(shù),私有變量及封裝的方法”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。