Python中__new__和__init__的区别与联系
生活随笔
收集整理的這篇文章主要介紹了
Python中__new__和__init__的区别与联系
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
__new__和__init__的區別主要表現在:它自身的區別及在Python中新式類和老式類的定義。
__new__ 負責對象的創建而 __init__ 負責對象的初始化。
__new__:創建對象時調用,會返回當前對象的一個實例
__init__:創建完對象后調用,對當前對象的一些實例初始化,無返回值
1. 在類中,如果__new__和__init__同時存在,會優先調用__new__
class ClsTest(object): def __init__(self): print("init") def __new__(cls,*args, **kwargs): print("new") ClsTest()執行結果出:
new2. 如果__new__返回一個對象的實例,會隱式調用__init__
class ClsTest(object): def __init__(self): print ("init") def __new__(cls,*args, **kwargs): print ("new %s"%cls) return object.__new__(cls, *args, **kwargs) ClsTest()執行結果為:
new <class '__main__.ClsTest'> init3. __new__方法會返回所構造的對象,__init__無返回值。
class ClsTest(object): def __init__(cls): cls.x = 2 print ("init") return cls ClsTest()執行結果為:
init Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __init__() should return None, not 'ClsTest'4. 若__new__沒有正確返回當前類cls的實例,那__init__是不會被調用的,即使是父類的實例也不行
class ClsTest1(object):passclass ClsTest2(ClsTest1):def __init__(self):print ("init")def __new__(cls,*args, **kwargs):print ("new %s"%cls)return object.__new__(ClsTest1, *args, **kwargs)b=ClsTest2() print (type(b))執行結果為:
new <class '__main__.ClsTest2'> <class '__main__.ClsTest1'>知識點
總結
以上是生活随笔為你收集整理的Python中__new__和__init__的区别与联系的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python获取计算机IP、mac地址、
- 下一篇: Python中lambda表达式的优缺点