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

可以看到 實例化對象 persion 也有兩個私有變量 _Persion__eat 和 _Persion__run ,嘗試直接用實例化對象 persion 調用私有變量。
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í)行結果如下圖:

可以看到通過這種方式,我們的 實例化對象 persion 也成功的調用了 PersionInfo 類 的私有函數(shù);但是既然是 私有函數(shù) ,那么目的就是不希望被實例化對象調用,所以我們還是按照編碼規(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í)行結果如下:
# >>> Neo 性別:男 ,他有一輛:'BMW'
# >>> 嘗試調用私有函數(shù) 私有函數(shù)與變量(屬性)['_PersionInfo_01__car', '_PersionInfo_01__info', '_PersionInfo_01__sex']
print(persion01._PersionInfo_01__info())
# >>> 執(zhí)行結果如下:
# >>> Neo 性別:男 ,他有一輛:'BMW'
Python 中的封裝
其實 Python 中并沒有 封裝 這個功能,而封裝只是針對 Python 中某種業(yè)務場景的一種概念而已。
封裝的概念 —> 將不對外的私有屬性或方法通過可以對外使用的函數(shù)而使用(類中定義的私有函數(shù)、私有方法只能在類的內部使用,外部無法訪問),這樣做的主要原因是:保護隱私,明確的區(qū)分內與外。
封裝的示例如下:
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í)行結果如下:
# >>> hello world
# >>> 我們可以看到 helloworld() 是基于 私有函數(shù) __hello() 來執(zhí)行的;
# >>> 所以我們是通過對外的函數(shù) helloworld() 調用了內部私有函數(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:查看明細",
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 = '轉入'
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('已成功存入!當前余額為:%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('已成功取出!當前余額為:%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í)行結果如下:
# >>> ********************歡迎使用資金交易管理系統(tǒng)********************
# >>> 1:申請存款
# >>> 2:申請取款
# >>> 3:查看明細
# >>> 4:查看余額
# >>> 0:退出系統(tǒng)
# >>> ************************************************************
# >>> 根據(jù)提示執(zhí)行對應的操作
PS:這個腳本并不完善,但是太晚了不想改了。
以上就是Python學習之私有函數(shù),私有變量及封裝詳解的詳細內容,更多關于Python私有函數(shù) 變量 封裝的資料請關注腳本之家其它相關文章!
相關文章
sklearn-SVC實現(xiàn)與類參數(shù)詳解
今天小編就為大家分享一篇sklearn-SVC實現(xiàn)與類參數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python中import和from-import的區(qū)別解析
這篇文章主要介紹了python中import和from-import的區(qū)別解析,本文通過實例代碼給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12

