1. 程式人生 > >Python基礎(十) __init__與__new__區別

Python基礎(十) __init__與__new__區別

ces weixin python2 code emp 類對象 nbsp 發現 構造

__init__與__new__區別:

__init__在python,其實是,在實例化之後執行的,用來初始化一些屬性,相當於構造函數,但是又不一樣

細心一些,通過參數會有所發現,其實__init__(self) self隱式的將,實例傳過來。

__new__在python中其實是,在實例化之前執行的,這個通過參數一樣可以看出

__new__(cls),cls是隱式的傳遞的類對象,並不是實例。因為__new__的任務就是,創建類實例並返回實例。

class temp(object):

    def __init__(self,txt):
        self.txt = txt
        
print __init__ def __new__(cls,txt): print __new__ print txt return super(temp,cls).__new__(cls) temp(what?)

結果:

C:\Python27\python.exe D:/weixin/temp/abc.py
__new__
what?
__init__

Process finished with exit code 0

Python基礎(十) __init__與__new__區別