Python基础第19天
生活随笔
收集整理的這篇文章主要介紹了
Python基础第19天
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?面向對象基礎講解二
一:雙下劃線開頭的attr方法
- __getattr__() ?只有屬性不存在時,會觸發
- __setattr__() ?設置屬性時,會觸發
- __delattr__() ?刪除屬性時會觸發
class Foo:x=1def __init__(self,y):self.y=ydef __setattr__(self,key,value): #__setattr__()print('執行__setattr__')# self.key=value #無限遞歸self.__dict__[key]=valuef1=Foo(10) print(f1.__dict__) f1.z=2 print(f1.__dict__)
class Foo:def __init__(self,name):self.name=name #只要是這種形式的就會觸發__setattr__def __getattr__(self, item):print('你找到屬性【%s】不存在'%item)def __setattr__(self, k, v):print('執行__setattr__',k,v)if type(v)is str:print('開始設置')self.__dict__[k]=velse:print('必須是字符串類型')def __delattr__(self, item):print('執行delattr',item)self.__dict__.pop(item)f1=Foo('alex') print(f1.name) print(f1.age) print(f1.__dict__) f1.age=18 #會觸發__setattr---- f1.gender='male' print(f1.__dict__) del f1.name print(f1.__dict__)#執行__setattr__ name alex #開始設置 #alex #你找到屬性【age】不存在 #None #{'name': 'alex'} #執行__setattr__ age 18 #必須是字符串類型 #執行__setattr__ gender male #開始設置 #{'name': 'alex', 'gender': 'male'} #執行delattr name #{'gender': 'male'}
二:授權(包裝的特性)
? ? ? 所有更新的功能都是由新類的某部分來處理,但是已存在的功能就授權給對象的默認參數。
? ? ? 實現授權的關鍵點就是覆蓋__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) #通過字符串找到自己屬性 # # # 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負載過高\n')
f1.write('內存剩余不足\n')
f1.write('硬盤剩余不足\n')
# 2017-03-13 09:14:29 cpu負載過高
2017-03-13 09:14:29 內存剩余不足
2017-03-13 09:14:29 硬盤剩余不足
? ? ?例子核心點是:利用getattr通過字符串找到自己屬性,通過返回給self.file擁有文件操作的功能。
?
轉載于:https://www.cnblogs.com/xyd134/p/6540134.html
總結
以上是生活随笔為你收集整理的Python基础第19天的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百度地图JavascriptApi Ma
- 下一篇: 斯坦福机器学习视频笔记 Week6 关于