一、attr屬性
1.1getattr屬性
class Foo: x=1 def __init__(self,y): self.y=y def __getattr__(self, item): print('執行__getattr__') f1=Foo(10) print(f1.y) print(f1,'y') f1.aaaa #調用一個對象不存在的屬性時,會自動觸發getattr
1.2delattra屬性
class Foo: x=1 def __init__(self,y): self.y=y def __delattr__(self, item): print('刪除操作__delattr__') f1=Foo(10) del f1.y print(f1.x) del f1.x #刪除屬性時,會觸發delattr
1.3setattr屬性
class Foo: x=1 def __init__(self,y): self.y=y def __setattr__(self,key,value): print('執行__setattr__') self.__dict__[key]=value f1=Foo(10) print(f1.__dict__) f1.z=2 #設置屬性時,會自動觸發__setattr__ print(f1.__dict__)
二、包裝和授權
2.1包裝的概念
包裝:python為大家提供了標准數據類型,以及豐富的內置方法,其實在很多場景下我們都需要基於標准數據類型來定制我們自己的數據類型,新增/改寫方法,這就用到了我們所學的繼承/派生知識(其他的標准類型均可以通過下面的方式進行二次加工)

# 包裝(二次加工標准類型) # 繼承 + 派生 的方式實現 定制功能 1、重新定義append方法 2、定制新的功能 class List(list): def append(self,object): #append類型必須是字符串 if type(object) is str: print("正在添加[%s]"%object) #list.append(self,object)#調用父類方法 super().append(object) else: print("必須是字符串類型") def show_midlle(self): #取傳入值得中間字符 mid_index = int(len(self)/2) return self[mid_index] f1 = List("helloworld") f1.append("SB") print(f1) f1.append(2222222) print(f1.show_midlle())
2.2授權的介紹
授權:授權是包裝的一個特性, 包裝一個類型通常是對已存在的類型的一些定制,這種做法可以新建,修改或刪除原有產品的功能。其它的則保持原樣。授權的過程,即是所有更新的功能都是由新類的某部分來處理,但已存在的功能就授權給對象的默認屬性。
實現授權的關鍵點就是覆蓋__getattr__方法

#組合的方式繼承了open函數的所有特性 class FileHandle: def __init__(self,filename,mode = "w",encoding = "utf-8"): self.file = open(filename,mode,encoding=encoding) self.mode = mode self.encoding = encoding def __getattr__(self,item): return getattr(self.file,item) f1 = FileHandle("a.txt") f1.write("1111\n")

組合的方式定制寫的方法 import time class FileHandle: def __init__(self,filename,mode = "a+",encoding = "utf-8"): self.file = open(filename,mode,encoding=encoding) self.mode = mode self.encoding = encoding def write(self,len): t = time.strftime("%Y-%m-%d %X") self.file.write("%s %s"%(t,len)) def __getattr__(self,item): return getattr(self.file,item) f1 = FileHandle("a.txt") f1.write("cpu負載過高\n") f1.write("內存剩余不足\n") f1.write("硬盤剩余不足\n")