python的class機制內置了很多特殊的方法來幫助使用者高度定制自己的類,
這些內置方法都是以雙下劃線開頭和結尾的,會在滿足某種條件時自動觸發,
我們以常用的__str__和__del__為例來簡單介紹它們的使用,
1、__str__方法
__str__方法會在物件被列印時自動觸發,print功能列印的就是它的回傳值,
我們通常基于方法來定制物件的列印資訊,該方法必須回傳字串型別
class People: def __init__(self, name, age): self.name = name self.age = age def __str__(self): # print('運行了...') return "<%s:%s>" %(self.name,self.age) obj = People('辣白菜同學', 18) # print(obj.__str__()) print(obj) # <'辣白菜同學':18> obj1=int(10) print(obj1) # 輸出結果 # <辣白菜同學:18> # 10
2、__del__方法
__del__會在物件被洗掉時自動觸發,
由于python自帶的垃圾回識訓制會自動清理python程式的資源,所以當一個物件只占用應用程式級資源時,完全沒必要為物件定制__del__方法,但在產生一個物件的同時涉及到申請系統資源(比如系統打開的檔案、網路連接等)的情況下,關于系統資源的回收,python的垃圾回識訓制便派不上用場了,需要我們為物件定制該方法,用來在物件被洗掉時自動觸發回收系統資源的操作
class People: def __init__(self, name, age): self.name = name self.age = age self.x = open('a.txt',mode='w') # self.x = 占據的是作業系統資源 def __del__(self): print('run...') # 發起系統呼叫,告訴作業系統回收相關的系統資源 self.x.close() obj = People('辣白菜同學', 18) # del obj # obj.__del__() print('============>')
# 輸出結果:
============>
run...
class People: def __init__(self, name, age): self.name = name self.age = age self.x = open('a.txt',mode='w') # self.x = 占據的是作業系統資源 def __del__(self): print('run...') # 發起系統呼叫,告訴作業系統回收相關的系統資源 self.x.close() obj = People('辣白菜同學', 18) del obj # obj.__del__() print('============>') # 輸出結果 # run... # ============>探索版二--View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/158680.html
標籤:Python
下一篇:十一、Python入門-進階
