Python中__new__和__init__区别
__new__:創建對象時調用,會返回當前對象的一個實例
__init__:創建完對象后調用,對當前對象的一些實例初始化,無返回值
1、在類中,如果__new__和__init__同時存在,會優先調用__new__
>>> class Data(object): ... def __new__(self): ... print "new" ... def __init__(self): ... print "init" ... >>> data = Data() new2、__new__方法會返回所構造的對象,__init__則不會。__init__無返回值。
>>> 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__返回一個對象的實例,會隱式調用__init__
If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
如果__new__不返回一個對象的實例,__init__不會被調用
<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.
在對象的實例創建完成后調用。參數被傳給類的構造函數。如果基類有__init__方法,子類必須顯示調用基類的__init__。
沒有返回值,否則會再引發TypeError錯誤。
http://www.cnblogs.com/itaceo-o/p/3300289.html
轉載于:https://www.cnblogs.com/gsblog/p/3368304.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Python中__new__和__init__区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从n个数中随机选取m个
- 下一篇: python 正则表达式应用——缩写词扩