python中__new__的奇怪行为

use*_*758 1 python

在阅读__new__时,我在StackOverflow本身遇到了一个例子.当我正在研究这个例子时,我稍微修改了代码.修改后的代码如下:

class A1(object):
    def __new__(cls):
        print 'in new'
    def __init__(self):
        print 'in init'

a = A1()

class A(object):
    _dict = dict()

    def __new__(cls):
        if 'key' in A._dict:
            print "EXISTS"
            return A._dict['key']
        else:
            print "NEW"
            return super(A, cls).__new__(cls)

    def __init__(self):
        print "INIT"
        A._dict['key'] = self
        print ""

a1 = A()
a2 = A()
a3 = A()
Run Code Online (Sandbox Code Playgroud)

输出如下:

in new
NEW
INIT

EXISTS
INIT

EXISTS
INIT
Run Code Online (Sandbox Code Playgroud)

也就是说,当为类'A1'创建实例时,只执行__new__,而对于类'A'实例,正在执行__new__和__init__.

我无法弄清楚原因.

Mar*_*ers 5

您没有在第一个示例中返回新实例; 你需要返回一个实例__init__被称为.

以下调用__new____init__方法:

class A1(object) :
    def __new__(cls) :
        print 'in new'
        return super(A1, cls).__new__(cls)

    def __init__(self) :
        print 'in init'
Run Code Online (Sandbox Code Playgroud)

演示:

>>> class A1(object) :
...     def __new__(cls) :
...         print 'in new'
...         return super(A1, cls).__new__(cls)
...     def __init__(self) :
...         print 'in init'
... 
>>> A1()
in new
in init
<__main__.A1 object at 0x106e5d090>
Run Code Online (Sandbox Code Playgroud)