Python中__new__和__init__区别
__new__:創(chuàng)建對(duì)象時(shí)調(diào)用,會(huì)返回當(dāng)前對(duì)象的一個(gè)實(shí)例
__init__:創(chuàng)建完對(duì)象后調(diào)用,對(duì)當(dāng)前對(duì)象的一些實(shí)例初始化,無(wú)返回值
1、在類中,如果__new__和__init__同時(shí)存在,會(huì)優(yōu)先調(diào)用__new__
>>> class Data(object): ... def __new__(self): ... print "new" ... def __init__(self): ... print "init" ... >>> data = Data() new2、__new__方法會(huì)返回所構(gòu)造的對(duì)象,__init__則不會(huì)。__init__無(wú)返回值。
>>> class Data(object): ... def __init__(cls): ... cls.x = 2 ... print "init" ... return cls ... >>> data = Data() init Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: __init__() should return None, not 'Data' >>> class Data(object): ... def __new__(cls): ... print "new" ... cls.x = 1 ... return cls ... def __init__(self): ... print "init" ... >>> data = Data() new >>> data.x =1 >>> data.x 1?
If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
如果__new__返回一個(gè)對(duì)象的實(shí)例,會(huì)隱式調(diào)用__init__
If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
如果__new__不返回一個(gè)對(duì)象的實(shí)例,__init__不會(huì)被調(diào)用
<class '__main__.B'> >>> class A(object): ... def __new__(Class): ... object = super(A,Class).__new__(Class) ... print "in New" ... return object ... def __init__(self): ... print "in init" ... >>> A() in New in init <__main__.A object at 0x7fa8bc622d90> >>> class A(object): ... def __new__(cls): ... print "in New" ... return cls ... def __init__(self): ... print "in init" ... >>> a = A() in New?
object.__init__(self[, ...])
Called when the instance is created. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self, [args...]). As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.
在對(duì)象的實(shí)例創(chuàng)建完成后調(diào)用。參數(shù)被傳給類的構(gòu)造函數(shù)。如果基類有__init__方法,子類必須顯示調(diào)用基類的__init__。
沒有返回值,否則會(huì)再引發(fā)TypeError錯(cuò)誤。
http://www.cnblogs.com/itaceo-o/p/3300289.html
轉(zhuǎn)載于:https://www.cnblogs.com/gsblog/p/3368304.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Python中__new__和__init__区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从n个数中随机选取m个
- 下一篇: websocket python爬虫_p