1.二次加工標準類型(包裝)app
class List(list): def append(self, a_objcet): if type(a_objcet) is str: super().append(a_objcet) else: print('請傳入字符轉類型') l1 = List('hello') l1.append(123) l1.append('world') print(l1)
運行結果:ui
請傳入字符轉類型 ['h', 'e', 'l', 'l', 'o', 'world'] Process finished with exit code 0
2.受權spa
受權是包裝的一個特性。受權的過程是全部更新的功能都是由新類的某部分來處理,但已存在的功能受權給對象的默認屬性。code
受權的關鍵就在於__getattr__方法。對象
# 建立一個open方法 class Open: def __init__(self,filname,mode='r',encoding='utf-8'): self.fil = open(filname,mode,encoding=encoding) self.mode = mode self.encoding = encoding def __getattr__(self, item): print('-------->',item,type(item)) return getattr(self.fil,item) f1 = Open('a.txt','w') print(f1.fil) print(f1.read) # 觸發__getattr__
運行結果:blog
<_io.TextIOWrapper name='a.txt' mode='w' encoding='utf-8'> --------> read <class 'str'> <built-in method read of _io.TextIOWrapper object at 0x7f718a0007e0> Process finished with exit code 0