Skip to main content
 首页 » 编程设计

python之__new__() 在 python 2.7.12 中不返回类实例时的继承

2025年02月15日9txw1958

我一直在阅读关于何时 __new__() 在 stackoverflow 上不返回类的实例 Inheritance when __new__() doesn't return instance of class我知道这个问题是针对 python 3 的。正如 Martijn Pieters 所说,它可以通过 name mangling 来完成。并直接在类里面手动调用它并在类里面完全初始化它。

我想在 python 2.7.12 中尝试一下。我可以处理第一种和第二种方法,但对于第三种方法会引发 TypeError

这是我的代码,第一次尝试:

class A: 
    def __new__(cls, p1, p2): 
        self = object.__new__(cls) 
        self.p1 = p1 
        self.p2 = p2 
        return [self] 
 
class B(A): 
    def __new__(cls, p3): 
        self = super(B,cls).__new__(cls,1,2) 
        self[0].p3 = p3 
        return self 

这给我 TypeError: super() argument 1 must be type, not classobj

第二次尝试:

class A(object): 
    def __new__(cls, p1, p2): 
        self = object.__new__(cls) 
        self.p1 = p1 
        self.p2 = p2 
        return [self]  #return not instance 
 
class B(A): 
    def __new__(cls, p3): 
        self = super(B,cls).__new__(cls,1,2) 
        self[0].p3 = p3 
        return self 

这给我 TypeError: __new__() takes exactly 2 arguments (1 given)

为什么会这样,可以在python 2.7.12中实现还是这个技术不兼容?

请您参考如下方法:

在您的第一次尝试中,您传递了一个旧式 类对象,但是super() 只接受新式类。

您需要继承自 object 以获得新样式的类,您在第二次尝试中正确地做到了这一点。您只是在创建实例时忘记传入参数:

>>> class A(object): 
...     def __new__(cls, p1, p2): 
...         self = object.__new__(cls) 
...         self.p1 = p1 
...         self.p2 = p2 
...         return [self] 
... 
>>> class B(A): 
...     def __new__(cls, p3): 
...         self = super(B, cls).__new__(cls, 1, 2) 
...         self[0].p3 = p3 
...         return self 
... 
>>> B() 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: __new__() takes exactly 2 arguments (1 given) 
>>> B(42) 
[<__main__.B object at 0x10241fa90>] 

您的错误告诉您 B.__new__ 需要两个参数,但只有 cls 被传入。