1. 程式人生 > >python 構造函數__new__(cls[,...]),析構器__del__()

python 構造函數__new__(cls[,...]),析構器__del__()

new log nbsp 實例 div 理解 pre you int

1 class capstr(str):
2     def __new__(cls,string):
3         string=string.upper()
4         return str.__new__(cls,string)
5 
6 a=capstr(ifuckyou)
7 print a

__new__是構造函數-------實例對象的建立

繼承字符串類str,把字符串大寫,然後用str.__new__()返回處理後的大寫字符串

不同於__init__(),init是初始化函數,new才是構造函數,真正返回一個實例對象的函數,init並不返回實例對象

__del__   當實例對象要被析構

當要銷毀一個對象時,__del__()就會被調用

主要是構造函數理解有一定的思考

python 構造函數__new__(cls[,...]),析構器__del__()