Python基础第19天
生活随笔
收集整理的這篇文章主要介紹了
Python基础第19天
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?面向?qū)ο蠡A(chǔ)講解二
一:雙下劃線開(kāi)頭的attr方法
- __getattr__() ?只有屬性不存在時(shí),會(huì)觸發(fā)
- __setattr__() ?設(shè)置屬性時(shí),會(huì)觸發(fā)
- __delattr__() ?刪除屬性時(shí)會(huì)觸發(fā)
class Foo:x=1def __init__(self,y):self.y=ydef __setattr__(self,key,value): #__setattr__()print('執(zhí)行__setattr__')# self.key=value #無(wú)限遞歸self.__dict__[key]=valuef1=Foo(10) print(f1.__dict__) f1.z=2 print(f1.__dict__)
class Foo:def __init__(self,name):self.name=name #只要是這種形式的就會(huì)觸發(fā)__setattr__def __getattr__(self, item):print('你找到屬性【%s】不存在'%item)def __setattr__(self, k, v):print('執(zhí)行__setattr__',k,v)if type(v)is str:print('開(kāi)始設(shè)置')self.__dict__[k]=velse:print('必須是字符串類型')def __delattr__(self, item):print('執(zhí)行delattr',item)self.__dict__.pop(item)f1=Foo('alex') print(f1.name) print(f1.age) print(f1.__dict__) f1.age=18 #會(huì)觸發(fā)__setattr---- f1.gender='male' print(f1.__dict__) del f1.name print(f1.__dict__)#執(zhí)行__setattr__ name alex #開(kāi)始設(shè)置 #alex #你找到屬性【age】不存在 #None #{'name': 'alex'} #執(zhí)行__setattr__ age 18 #必須是字符串類型 #執(zhí)行__setattr__ gender male #開(kāi)始設(shè)置 #{'name': 'alex', 'gender': 'male'} #執(zhí)行delattr name #{'gender': 'male'}
二:授權(quán)(包裝的特性)
? ? ? 所有更新的功能都是由新類的某部分來(lái)處理,但是已存在的功能就授權(quán)給對(duì)象的默認(rèn)參數(shù)。
? ? ? 實(shí)現(xiàn)授權(quán)的關(guān)鍵點(diǎn)就是覆蓋__getattr__方法。
import time class Open:def __init__(self,filename,mode='r',encoding='utf-8'):# self.filename=filenameself.file=open(filename,mode,encoding=encoding) #封裝了文件操作的方法(繼承)self.mode=modeself.encoding=encodingdef write(self,line):t=time.strftime('%Y-%m-%d %X')self.file.write('%s %s'%(t,line))def __getattr__(self, item):# print(item,type(item))return getattr(self.file,item) #通過(guò)字符串找到自己屬性 # # # f1=Open('a.txt','w') print(f1.file) print('--->',f1.read)# sys_f=open('b.txt','w+') # print(getattr(sys_f,'read'))print(f1.write) f1.write('1234\n') #2017-03-13 09:11:03 1234 # f1.seek(0) #f1.write('cpu負(fù)載過(guò)高\(yùn)n')
f1.write('內(nèi)存剩余不足\n')
f1.write('硬盤(pán)剩余不足\n')
# 2017-03-13 09:14:29 cpu負(fù)載過(guò)高
2017-03-13 09:14:29 內(nèi)存剩余不足
2017-03-13 09:14:29 硬盤(pán)剩余不足
? ? ?例子核心點(diǎn)是:利用getattr通過(guò)字符串找到自己屬性,通過(guò)返回給self.file擁有文件操作的功能。
?
轉(zhuǎn)載于:https://www.cnblogs.com/xyd134/p/6540134.html
總結(jié)
以上是生活随笔為你收集整理的Python基础第19天的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 百度地图JavascriptApi Ma
- 下一篇: websocket python爬虫_p