Python : 调用超类的 __new__ 方法

Python : calling __new__ method of superclass

我有两个 python 类 定义如下:

class A(object) : 

    def __init__(self, param) : 
        print('A.__init__ called')
        self.param = param

    def __new__(cls, param) :
        print('A.__new__ called') 
        x = object.__new__(A)
        x._initialize()    # initialization code
        return x

class B(A) : 

    def __init__(self, different_param) : 
        print('B.__init__ called')

    def __new__(cls, different_param) : 
        print('B.__new__ called')
        # call __new__ of class A, passing "param" as parameter
        # and get initialized instance of class B
        # something like below
        b = object.__new__(B)
        param = cls.convert_param(different_param)
        return super(B, cls).__new__(b, param)    # I am expecting something
                                                  # similar to this

    @staticmethod
    def convert_param(param) : 
        return param 

class Bclass A 的子类。两者之间的区别 类 是传递给 class B 的参数与 class A 预期的参数格式不同。所以调用了classBconvert_param方法,将参数转换为兼容class A__new__方法。

我卡在了想从 class B__new__ 方法调用 class A__new__ 方法的部分,因为有很多在那里发生的初始化,然后取回 class B 的初始化实例。

我很难弄明白这一点。请帮助。

convert_param 应该是 staticmethodclassmethod 并且您不希望从 B 调用 object.__new__(否则,您本质上是在尝试创建 B 的两个新实例,而不是一个)。如果 convert_paramstaticmethodclassmethod,那么您可以在 之前进行参数转换 你有一个实例(例如 __new__ 已在超类上调用):

class B(A):
    @staticmethod
    def convert_param(params):
        # do magic
        return params

    def __new__(cls, params):
        params = cls.convert_params(params)
        return super(B, cls).__new__(cls, params)

此外,您需要稍微更改 A__new__ 以不硬编码从 object.__new__:

返回的实例类型
class A(object) : 
    def __new__(cls, param) :
        print('A.__new__ called') 
        x = super(A, cls).__new__(cls)
        x._initialize()    # initialization code
        return x