Python學(xué)習(xí)之私有函數(shù),私有變量及封裝詳解
通過學(xué)習(xí)私有函數(shù)與私有變量,可以更好的完善 類的開發(fā) ,從而豐滿我們的場景與實現(xiàn)方案。
什么是私有函數(shù)和私有變量
私有函數(shù)與私有變量中的私有是什么意思? —> 簡單理解就是獨自擁有、不公開、不分享的意思。放到函數(shù)與變量中就是獨自擁有的函數(shù)與獨自擁有的變量,并且不公開。這樣我們就理解了什么是私有函數(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ù)與私有變量:在 類變量 與 類函數(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 中并沒有 封裝 這個功能,而封裝只是針對 Python 中某種業(yè)務(wù)場景的一種概念而已。
封裝的概念 —> 將不對外的私有屬性或方法通過可以對外使用的函數(shù)而使用(類中定義的私有函數(shù)、私有方法只能在類的內(nèi)部使用,外部無法訪問),這樣做的主要原因是:保護隱私,明確的區(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í)
需求:
用類和對象實現(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:查看明細",
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('請點擊任意鍵以繼續(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('請點擊任意鍵以繼續(xù)...')
else:
print('您輸入的取出金額超過余額,無法操作!請重新輸入')
input('請點擊任意鍵以繼續(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('請點擊任意鍵以繼續(xù)...')
def check_money(self):
print('賬戶余額為:%s元' % self.money)
input('請點擊任意鍵以繼續(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('請點擊任意鍵以繼續(xù)...')
money_exchange = MoneyExchange()
while True:
money_exchange.welcome_menu()
money_exchange.user_input()
# >>> 執(zhí)行結(jié)果如下:
# >>> ********************歡迎使用資金交易管理系統(tǒng)********************
# >>> 1:申請存款
# >>> 2:申請取款
# >>> 3:查看明細
# >>> 4:查看余額
# >>> 0:退出系統(tǒng)
# >>> ************************************************************
# >>> 根據(jù)提示執(zhí)行對應(yīng)的操作
PS:這個腳本并不完善,但是太晚了不想改了。
以上就是Python學(xué)習(xí)之私有函數(shù),私有變量及封裝詳解的詳細內(nèi)容,更多關(guān)于Python私有函數(shù) 變量 封裝的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用python提取PowerPoint幻燈片中表格并保存到文本及Excel文件
owerPoint作為廣泛使用的演示工具,常被用于展示各類數(shù)據(jù)報告和分析結(jié)果,其中,表格以其直觀性和結(jié)構(gòu)性成為闡述數(shù)據(jù)關(guān)系的不二之選,本文將介紹如何使用Python來提取PowerPoint幻燈片中的表格,并將表格數(shù)據(jù)寫入文本文件以及Excel文件,需要的朋友可以參考下2024-06-06
使用python實現(xiàn)快速搭建簡易的FTP服務(wù)器
本文給大家推薦的是如何使用Python實現(xiàn)快速搭建簡易的FTP服務(wù)器的方法,非常的簡單,有需要的小伙伴可以參考下2018-09-09
pandas中DataFrame修改index、columns名的方法示例
這篇文章主要介紹了pandas中DataFrame修改index、columns名的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
tf.nn.conv2d與tf.layers.conv2d的區(qū)別及說明
這篇文章主要介紹了tf.nn.conv2d與tf.layers.conv2d的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
Python 操作mysql數(shù)據(jù)庫查詢之fetchone(), fetchmany(), fetchall()用法示例
這篇文章主要介紹了Python 操作mysql數(shù)據(jù)庫查詢之fetchone(), fetchmany(), fetchall()用法,結(jié)合實例形式分析了Python使用pymysql模塊的fetchone(), fetchmany(), fetchall()方法進行mysql數(shù)據(jù)庫查詢的操作技巧,需要的朋友可以參考下2019-10-10

