zoukankan      html  css  js  c++  java
  • Python中__new__和__init__的区别与联系

    __new__ 负责对象的创建而 __init__ 负责对象的初始化。

    __new__:创建对象时调用,会返回当前对象的一个实例

    __init__:创建完对象后调用,对当前对象的一些实例初始化,无返回值

    1. 在类中,如果__new__和__init__同时存在,会优先调用__new__

    1
    2
    3
    4
    5
    6
    7
    class ClsTest(object):
        def __init__(self):
            print("init")
        def __new__(cls,*args, **kwargs):
            print("new")
      
    ClsTest()

    输出:

    1
    new

    2. 如果__new__返回一个对象的实例,会隐式调用__init__

    代码实例:

    1
    2
    3
    4
    5
    6
    7
    8
    class ClsTest(object):
        def __init__(self):
            print ("init")
        def __new__(cls,*args, **kwargs):
            print ("new %s"%cls)
            return object.__new__(cls*args, **kwargs)
      
    ClsTest()

    输出:

    1
    2
    new <class '__main__.ClsTest'>
    init

    3. __new__方法会返回所构造的对象,__init__则不会。__init__无返回值。

    1
    2
    3
    4
    5
    6
    7
    class ClsTest(object):
         def __init__(cls):
                 cls.x = 2
                 print ("init")
                 return cls
      
    ClsTest()

    输出:

    1
    2
    3
    4
    init
    Traceback (most recent call last):
      File "<stdin>", line 1in <module>
    TypeError: __init__() should return Nonenot 'ClsTest'

    4. 若__new__没有正确返回当前类cls的实例,那__init__是不会被调用的,即使是父类的实例也不行

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class ClsTest1(object):
        pass
      
    class 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))

     输出:

    1
    2
    new <class '__main__.ClsTest2'>
    <class '__main__.ClsTest1'>

  • 相关阅读:
    407 Trapping Rain Water II 接雨水 II
    406 Queue Reconstruction by Height 根据身高重建队列
    405 Convert a Number to Hexadecimal 数字转换为十六进制数
    404 Sum of Left Leaves 左叶子之和
    403 Frog Jump 青蛙过河
    402 Remove K Digits 移掉K位数字
    401 Binary Watch 二进制手表
    400 Nth Digit 第N个数字
    398 Random Pick Index 随机数索引
    397 Integer Replacement 整数替换
  • 原文地址:https://www.cnblogs.com/cheyunhua/p/11351698.html
Copyright © 2011-2022 走看看