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:這種隱藏只是一種語法上變形操作,并不會(huì)將屬性真正隱藏起來
# print(Foo.__dict__)
# print(f.__dict__)
# print(f._Foo__Name)
# print(f._Foo__N)
#2:這種語法級(jí)別的變形,是在類定義階段發(fā)生的,并且只在類定義階段發(fā)生
# Foo.__x=123123123123123123123123123123123123123123
# print(Foo.__dict__)
# print(Foo.__x)
# f.__x=123123123
# print(f.__dict__)
# print(f.__x)
#3:在子類定義的__x不會(huì)覆蓋在父類定義的__x,因?yàn)樽宇愔凶冃纬闪?#xff1a;_子類名__x,而父類中變形成了:_父類名__x,即雙下滑線開頭的屬性在繼承給子類時(shí),子類是無法覆蓋的。
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:封裝數(shù)據(jù)屬性:將屬性隱藏起來,然后對(duì)外提供訪問屬性的接口,關(guān)鍵是我們?cè)诮涌趦?nèi)定制一些控制邏輯從而嚴(yán)格控制使用對(duì)數(shù)據(jù)屬性的使用
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:封裝函數(shù)屬性:為了隔離復(fù)雜度
#取款是功能,而這個(gè)功能有很多功能組成:插卡、密碼認(rèn)證、輸入金額、打印賬單、取錢
#對(duì)使用者來說,只需要知道取款這個(gè)功能即可,其余功能我們都可以隱藏起來,很明顯這么做
#隔離了復(fù)雜度,同時(shí)也提升了安全性
class ATM:
def __card(self):
print('插卡')
def __auth(self):
print('用戶認(rèn)證')
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
轉(zhuǎn)載于:https://www.cnblogs.com/wangmengzhu/p/7402947.html
總結(jié)
以上是生活随笔為你收集整理的Python__封装的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Testing for SSL rene
- 下一篇: 用Python爬虫爬取炉石原画卡牌图片