Python學(xué)習(xí)之私有函數(shù),私有變量及封裝詳解
通過學(xué)習(xí)私有函數(shù)與私有變量,可以更好的完善 類的開發(fā) ,從而豐滿我們的場景與實(shí)現(xiàn)方案。
什么是私有函數(shù)和私有變量
私有函數(shù)與私有變量中的私有是什么意思? —> 簡單理解就是獨(dú)自擁有、不公開、不分享的意思。放到函數(shù)與變量中就是獨(dú)自擁有的函數(shù)與獨(dú)自擁有的變量,并且不公開。這樣我們就理解了什么是私有函數(shù)與私有變量。
- 無法被實(shí)例化后的對象調(diào)用的類中的函數(shù)與變量
- 雖然無法被實(shí)例化后的對象調(diào)用,但是在 類的內(nèi)部我們可以 調(diào)用私有函數(shù)與私有變量
- 私有函數(shù)與私有變量的目的:只希望類內(nèi)部的業(yè)務(wù)調(diào)用使用,不希望被實(shí)例化對象調(diào)用使用
- 既然有私有函數(shù)與私有變量,其實(shí)能被實(shí)例化對象調(diào)用的函數(shù)與變量就是公有函數(shù)與公有變量,不過一般我們都稱之為函數(shù)與變量。
私有函數(shù)與私有變量的定義方法
如何定義私有函數(shù)與私有變量:在 類變量 與 類函數(shù) 前添加 __ (2個(gè)下橫線)即可定義私有函數(shù)與私有變量;變量或函數(shù)的后面無需添加,左右都有兩個(gè)下橫線,是 類的內(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 最喜歡的健身方式是 '跑步' 和 '游泳'
我們再試一下 通過 實(shí)例化對象 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'
# >>> 再一次證明 實(shí)例化對象是不可以調(diào)用私有函數(shù)的
那么事實(shí)真的是 實(shí)例化對象就沒有辦法調(diào)用 私有函數(shù) 了么?其實(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ù) 查看一下 實(shí)例化對象 persion 中都有哪些函數(shù)?
print(dir(persion))

可以看到 實(shí)例化對象 persion 也有兩個(gè)私有變量 _Persion__eat 和 _Persion__run ,嘗試直接用實(shí)例化對象 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ù) 查看一下 實(shí)例化對象 persion 中都有哪些函數(shù)?
print(dir(persion))
print(persion._PersionInfo__eat())
print(persion._PersionInfo__run())
# >>> 執(zhí)行結(jié)果如下圖:

可以看到通過這種方式,我們的 實(shí)例化對象 persion 也成功的調(diào)用了 PersionInfo 類 的私有函數(shù);但是既然是 私有函數(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 中的封裝
其實(shí) Python 中并沒有 封裝 這個(gè)功能,而封裝只是針對 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 中的 封裝的概念。
面向?qū)ο缶幊绦【毩?xí)
需求:
用類和對象實(shí)現(xiàn)銀行賬戶的資金交易管理,包括存款、取款和打印交易詳情,交易詳情中包含每次交易的時(shí)間、存款或者取款的金額、每次交易后的余額。
腳本示例如下:
#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('請輸入選項(xiàng):'))
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)的操作
PS:這個(gè)腳本并不完善,但是太晚了不想改了。
以上就是Python學(xué)習(xí)之私有函數(shù),私有變量及封裝詳解的詳細(xì)內(nèi)容,更多關(guān)于Python私有函數(shù) 變量 封裝的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
sklearn-SVC實(shí)現(xiàn)與類參數(shù)詳解
今天小編就為大家分享一篇sklearn-SVC實(shí)現(xiàn)與類參數(shù)詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python中import和from-import的區(qū)別解析
這篇文章主要介紹了python中import和from-import的區(qū)別解析,本文通過實(shí)例代碼給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12
Python使用os模塊實(shí)現(xiàn)更高效地讀寫文件
os是python標(biāo)準(zhǔn)庫,包含幾百個(gè)函數(shù)常用路徑操作、進(jìn)程管理、環(huán)境參數(shù)等好多類。本文將使用os模塊實(shí)現(xiàn)更高效地讀寫文件,感興趣的可以學(xué)習(xí)一下2022-07-07

