實現授權的關鍵點就是覆蓋__getattr__()方法,在代碼中包含一個對getattr()內建函數的調用。
特別調用getattr()以得到默認對象屬性(數據屬性或者方法)并返回它以便訪問或調用。
特殊方法__getattr__()的工作方式是,當搜索一個屬性時,任何局部對象首先被找到(定制的對象)。如果搜索
失敗了,則__getattr__()會被調用,然后調用getattr()得到一個對象默認行為。
當引用一個屬性時,解釋器將試著在局部名稱空間中查找那個名字,比如一個自定義的方法或局部實例屬性。
如果沒有在局部字典中找到,則搜索類名名稱空間,以防一個類屬性被訪問。最后,如果兩類搜索都失敗了,
搜索則對原對象開始授權請求,此時,__getattr__()會被調用。
授權(也是一種包裝,關鍵點是覆蓋__getattr__方法)
基于基本類型定制自己的類型
import time
class FileHandle:
def __init__(self,filename,mode='r',encoding='utf-8'):
# self.filename=filename
self.file=open(filename,mode,encoding=encoding) #組合
self.mode=mode
self.encoding=encoding
def write(self,line):
print('------------>',line)
t=time.strftime('%Y-%m-%d %X')
self.file.write('%s %s' %(t,line))
def __getattr__(self, item):
# print(item,type(item))
# self.file.read
return getattr(self.file,item)
f1=FileHandle('a.txt','w+')
# print(f1.file)
# print(f1.__dict__)
# print('==>',f1.read) #觸發__getattr__
# print(f1.write)
f1.write('1111111111111111\n')
f1.write('cpu負載過高\n')
f1.write('內存剩余不足\n')
f1.write('硬盤剩余不足\n')
# f1.seek(0)
# print('--->',f1.read())
包裝
二次加工標準類型(包裝繼承加派生實現)
class List(list):
def append(self, p_object):
if type(p_object) is str:
# self.append(p_object) #導致無限遞歸
super().append(p_object)
else:
print('只能添加字符串類型')
def show_midlle(self):
mid_index=int(len(self)/2)
return self[mid_index]
# l2=list('hell oworld')
# print(l2,type(l2))
l1=List('helloworld')
# print(l1,type(l1))
# print(l1.show_midlle())
l1.append(1111111111111111111111)
l1.append('SB')
print(l1)