Python__封装
#先看如何隱藏
class Foo:
__N=111111 #_Foo__N
def __init__(self,name):
self.__Name=name #self._Foo__Name=name
def __f1(self): #_Foo__f1
print('f1')
def f2(self):
self.__f1() #self._Foo__f1()
f=Foo('egon')
# print(f.__N)
# f.__f1()
# f.__Name
# f.f2()
#這種隱藏需要注意的問題:
#1:這種隱藏只是一種語法上變形操作,并不會將屬性真正隱藏起來
# print(Foo.__dict__)
# print(f.__dict__)
# print(f._Foo__Name)
# print(f._Foo__N)
#2:這種語法級別的變形,是在類定義階段發生的,并且只在類定義階段發生
# Foo.__x=123123123123123123123123123123123123123123
# print(Foo.__dict__)
# print(Foo.__x)
# f.__x=123123123
# print(f.__dict__)
# print(f.__x)
#3:在子類定義的__x不會覆蓋在父類定義的__x,因為子類中變形成了:_子類名__x,而父類中變形成了:_父類名__x,即雙下滑線開頭的屬性在繼承給子類時,子類是無法覆蓋的。
class Foo:
def __f1(self): #_Foo__f1
print('Foo.f1')
def f2(self):
self.__f1() #self._Foo_f1
class Bar(Foo):
def __f1(self): #_Bar__f1
print('Bar.f1')
# b=Bar()
# b.f2()
?
#封裝不是單純意義的隱藏
#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()
# _x=123
轉載于:https://www.cnblogs.com/wangmengzhu/p/7402947.html
總結
以上是生活随笔為你收集整理的Python__封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Testing for SSL rene
- 下一篇: 用Python爬虫爬取炉石原画卡牌图片