Skip to main content
 首页 » 编程设计

python之__new__ 在 python 中的奇怪行为

2025年05月04日63lvdongjie

在阅读有关 __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() 

输出如下:

in new 
NEW 
INIT 
 
EXISTS 
INIT 
 
EXISTS 
INIT 

也就是说,当为类“A1”创建实例时,仅执行 __new__,而对于类“A”实例,同时执行 __new__ 和 __init__。

我无法找出原因。

请您参考如下方法:

您在第一个示例中没有返回新实例;您需要为 __init__ 返回一个实例以在 上调用。

以下调用了 __new__ 和 __init__ 方法:

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

演示:

>>> 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>