最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python學習之私有函數(shù),私有變量及封裝詳解

 更新時間:2022年03月10日 08:49:07   作者:渴望力量的哈士奇  
私有函數(shù)與私有變量中的私有就是獨自擁有、不公開、不分享的意思。放到函數(shù)與變量中就是獨自擁有的函數(shù)與獨自擁有的變量,并且不公開。本文將通過示例詳細講解Python中的私有函數(shù)、私有變量及封裝,感興趣的可以學習一下

通過學習私有函數(shù)與私有變量,可以更好的完善 類的開發(fā) ,從而豐滿我們的場景與實現(xiàn)方案。

什么是私有函數(shù)和私有變量

私有函數(shù)與私有變量中的私有是什么意思? —> 簡單理解就是獨自擁有、不公開、不分享的意思。放到函數(shù)與變量中就是獨自擁有的函數(shù)與獨自擁有的變量,并且不公開。這樣我們就理解了什么是私有函數(shù)與私有變量。

  • 無法被實例化后的對象調(diào)用的類中的函數(shù)與變量
  • 雖然無法被實例化后的對象調(diào)用,但是在 類的內(nèi)部我們可以 調(diào)用私有函數(shù)與私有變量
  • 私有函數(shù)與私有變量的目的:只希望類內(nèi)部的業(yè)務調(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è)務場景的一種概念而已。

封裝的概念 —> 將不對外的私有屬性或方法通過可以對外使用的函數(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ū)ο缶幊绦【毩?/h2>

需求:

用類和對象實現(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('已成功存入!當前余額為:%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í)行結(jié)果如下:
# >>> ********************歡迎使用資金交易管理系統(tǒng)********************
# >>> 1:申請存款
# >>> 2:申請取款
# >>> 3:查看明細
# >>> 4:查看余額
# >>> 0:退出系統(tǒng)
# >>> ************************************************************

# >>> 根據(jù)提示執(zhí)行對應的操作

PS:這個腳本并不完善,但是太晚了不想改了。

以上就是Python學習之私有函數(shù),私有變量及封裝詳解的詳細內(nèi)容,更多關(guān)于Python私有函數(shù) 變量 封裝的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

和政县| 长乐市| 乳源| 开封市| 墨脱县| 都匀市| 竹北市| 额敏县| 永寿县| 白银市| 育儿| 沙河市| 湟中县| 翁源县| 上饶市| 静安区| 洛浦县| 陇川县| 鄱阳县| 探索| 东兴市| 大安市| 古浪县| 绍兴市| 时尚| 海阳市| 柞水县| 邹城市| 溧水县| 龙里县| 彩票| 武穴市| 平利县| 仙游县| 昭平县| 临夏县| 珲春市| 桂阳县| 惠水县| 临城县| 大同县|