1. 程式人生 > >Python 封裝

Python 封裝

實現 sel style 不足 屬性和方法 調用 def 函數 pan

定義:

  封裝不僅僅是隱藏屬性和方法是具體明確區分內外,使得類實現者可以修改封裝內的東西而不影響外部調用者的代碼;而外部使用用者只知道一個接口(函數),只要接口(函數)名、參數不變,使用者的代碼永遠無需改變。這就提供一個良好的合作基礎——或者說,只要接口這個基礎約定不變,則代碼改變不足為慮。

  封裝可分為封裝屬性與封裝函數

實例:

#1:封裝數據屬性:將屬性隱藏起來,然後對外提供訪問屬性的接口,關鍵是我們在接口內定制一些控制邏輯從而嚴格控制使用對數據屬性的使用
class People:
    def __init__(self,name,age):
        if not isinstance(name,str):
            
raise TypeError(%s must be str %name) if not isinstance(age,int): raise TypeError(%s must be int %age) self.__Name=name self.__Age=age def tell_info(self): print(<名字:%s 年齡:%s> %(self.__Name,self.__Age)) def set_info(self,x,y):
if not isinstance(x,str): raise TypeError(%s must be str %x) if not isinstance(y,int): raise TypeError(%s must be int %y) self.__Name=x self.__Age=y p=People(egon,18) p.tell_info() p.set_info(Egon,19) p.set_info(Egon,19) p.tell_info()
#2:封裝函數屬性:為了隔離復雜度 #取款是功能,而這個功能有很多功能組成:插卡、密碼認證、輸入金額、打印賬單、取錢 #對使用者來說,只需要知道取款這個功能即可,其余功能我們都可以隱藏起來,很明顯這麽做 #隔離了復雜度,同時也提升了安全性 class ATM: def __card(self): print(插卡) def __auth(self): print(用戶認證) def __input(self): print(輸入取款金額) def __print_bill(self): print(打印賬單) def __take_money(self): print(取款) def withdraw(self): self.__card() self.__auth() self.__input() self.__print_bill() self.__take_money() a=ATM() a.withdraw()

Python 封裝