Python __init__ 特殊方法

來源:互聯網
上載者:User

標籤:append   方法   列印   第一個   ast   define   需要   font   操作   

在Python中有很多以雙底線開頭且以雙底線結尾的固定方法。他們會在特定的時機被觸發執行。

__init__ 就是其中之一,它會在執行個體化之後自動被調用。以完成執行個體的初始化。

>>> class test:   #定義一個類def func(self):print(‘手動調用函數:‘,id(self))   #列印參數的id>>> a = test()    #執行個體化對象a>>> a.func()      #用執行個體a調用函數func(),會把執行個體a當成一個參數,並且第一個傳入到函數func()中。手動調用函數: 1794999510856>>> >>> class test:     #定義一個類,裡面封裝的函數使用了__init__特殊方法,這個方法會在初始化執行個體時自動調用def __init__(self):print(‘初始化執行個體時自動調用:‘,id(self))>>> a = test()   #執行個體化對象a,此時它會自動調用__init__,不需要類似a.func()的操作。初始化執行個體時自動調用: 1794999587840>>> 

“析構”問題引入

>>> a = [1,2,3]>>> b =a           #變數的指向>>> b[1, 2, 3]>>> a.append(5)>>> a[1, 2, 3, 5]>>> b[1, 2, 3, 5]>>> del a      #刪除一個變數的指向。>>> aTraceback (most recent call last):  File "<pyshell#28>", line 1, in <module>    aNameError: name ‘a‘ is not defined>>> b[1, 2, 3, 5]>>> 

  

  

Python __init__ 特殊方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.