python進階(四)~~~魔術方法
魔術方法
在python中,以雙下劃線開頭、雙下劃線結尾的方法我們稱之為魔術方法。例如__init__
魔術方法是python內部定義好的,我們不需要去創建。
1.__new__方法和單例模式
__new__方法:Create and return a new object.創建對象時觸發
class Hero(object): def __init__(self,name): # 對對象進行初始化 print("這是init方法") self.name=name def __new__(cls,*args,**kwargs): # 創建對象 print("這是new方法") return super().__new__(cls) # 必須返回原方法 創建對象的功能。如果缺少改行,h1返回值為None h1=Hero("musen") print(h1.name)
應用:
1. 重寫new方法,返回其他的類對象;
2.單例模式: 通常類每次實例化都會創建一個對象,通過單例模式可以實現限制 一個類只創建一個對象共用;
單例模式實現思路:
1.創建一個類屬性記錄是否創建過對象;
2.在__new__方法中對類屬性做出判斷:如果沒有創建,就新建一個對象并修改1種屬性值;如果創建過,直接返回已創建的對象;
class Myclass(object): '''單例模式類''' instance=None def __new__(cls,*args,**kwargs): # 創建對象 if not cls.instance: cls.instance=object.__new__(cls) return cls.instance else: return cls.instance h1=Myclass() h2=Myclass() h3=Myclass() print(id(h1),id(h2),id(h3))
2.上下文管理器
通過with實現,底層使用兩個魔術方法:object.__enter__()、object.__exit__()。一個類中只要使用了這兩個方法,那么該類就實現了上下文協議,就是一個上下文管理器;
object.__enter__(self): 輸入此對象運行時使用的相關上下文;
object.__exit__(self,exc_type,exc_val,exc_tb): 參數:異常類型、異常值、異常回溯
class Myopen(object): def __init__(self,filename,mode,encoding): self.filename=filename self.mode=mode self.encoding=encoding self.f=open(self.filename,self.mode,encoding=self.encoding) def __enter__(self): return self.f # 返回打開的文件 def __exit__(self,exc_type,exc_val,exc_tb): self.f.close() # 關閉文件
print(exc_type,exc_val,exc_tb) #當執行出錯時,打印出錯誤信息
with Myopen("1.txt","r",encoding="utf8") as f: print(f.read())
上下文管理器的應用舉例:
class Testcase(Myopen,unittest.TestCase): def __init__(self,*args,**kwargs): Myopen.__init__(self,*args,**kwargs) self,*args,**kwargs.__init__(self,*args,**kwargs) print("__init__") t=Testcase()
3.__call__方法 : 在對象使用括號時被觸發,使類創建的對象像函數一樣可以被引用
class Test(object): def __call__(self): print("觸發了call方法") t=Test() t() # 觸發了call方法
4.__str__方法、__repr__方法
__str__方法:print()、str()、format() 觸發
__repr__方法:交互環境>>>下直接輸入變量時、repr轉換對象時 觸發;當找不到__str__方法,只有__repr__方法時,上述3種均觸發__repr__方法
應用:打印類的一些屬性
class Hero(object): def __init__(self,name): self.name=name def __str__(self): return self.name h=Hero('musen') print(h)
5. 算術運算的實現
__add__(slef,other): 相加 +,以+觸發
__sub__(slef,other): 相減 -
__mul__(slef,other): 相乘 *
__truediv__(slef,other): 定義真除法 /
__floordiv__(slef,other): 定義整數除法 //
__mod__(slef,other): 定義取余算法 %
class Mystr(object): def __init__(self,value): self.value=value def __str__(self): return self.value def __add__(self,other): # self代表實例本身,other代表其他 return Mystr(F'{self.value}{other.value}')
def __sub__(self,other):
return self.value.replace(other.value,'')
s1=Mystr("aaa") s2=Mystr("bbb") print(s1+s2)

浙公網安備 33010602011771號