Python中__new__和__init__的簡單介紹
阿新 • • 發佈:2018-11-17
__init__方法
相信大家對__init__方法是很熟悉了,它是在例項化類的時候被呼叫,用於初始化該物件。
class Student:
def __init__(self,name,number):
self.name=name
self.number=number
def __str__(self):
return 'Student:%s(%s)'%(self.name,self.number)
stu=Student('Michael',24)
print(stu)
執行結果為:
Student:Michael(24)
可以看到當建立一個物件時,會呼叫類的__init__方法對其進行處理。
__new__
那麼__new__方法又是幹什麼的呢?其實當我們例項化一個物件時,我們首先呼叫的方法就是__new__,而不是__init__。
class Student(object): def __new__(cls,name,age): print("__new__") print(cls) return object.__new__(cls) #return super().__new__(cls) def __init__(self,name,number): print("__init__") self.name=name self.number=number def __str__(self): return 'Student:%s(%s)'%(self.name,self.number) stu=Student('Michael',24) print(stu)
執行結果為:
__new__
<class '__main__.Student'>
__init__
Student:Michael(24)
可以看到__new__方法在__init__之前被呼叫,其中cls代表要例項化的類,__new__方法會返回一個cls類的例項化物件,這就是__init__方法中的self。
兩者關係的總結
經過上述的簡要分析,當例項化一個類時,整個流程是這樣的:
- 呼叫該類的__new__方法,其實該類中也是呼叫的object或父類的__new__方法,需傳入需要例項化的類,並返回一個該類的例項化物件。
- 呼叫__init__方法,對該物件進行初始化,其中self便是__new__方法中返回的例項化物件。