python魔法方法之構造和析構

來源:互聯網
上載者:User

標籤:self   span   rect   記憶體回收機制   不可變類   一個   引用計數   nbsp   引用   

python的類執行個體化的時候會預設執行該類的構造方法_init_

1 class Rectangle:2     def __init__(self,x,y):3         self.x=x4         self.y=y5     def getArea(self):6         return self.x * self.y7 r = Rectangle(5,10)8 print(r.getArea())

python中一個類被建立時最先執行的方法是new方法,當需要修改某些不可變類型的對象時需要重寫他的new方法

1 #重寫int類的new方法使得到的數為正數2 class A(int):3     def __new__(cls, value):4         return super(A, cls).__new__(cls, abs(value))5 a= A(-5)6 print(a)7 8 5

python中有記憶體回收機制,Python中所有的變數其實都是對記憶體對象的引用。只有當一個記憶體對象的引用計數降為0,即沒有被變數引用時,解譯器的記憶體回收機制才會回收這塊記憶體。只有當記憶體被真正回收時,__del__方法才會被調用。

 1 class B: 2     def __init__(self): 3         print(‘init‘) 4     def __del__(self): 5         class_name = self.__class__.__name__ 6         print (class_name,"destroy") 7          8 b1= B() 9 init10 b2= b111 del b212 del b113 B destroy

 

python魔法方法之構造和析構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.