Python:调用超类的__new__方法

时间:2016-07-21 20:40:16

标签: python inheritance override subclass

我有两个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所期望的参数格式不同。因此,调用convert_param classB方法可将参数转换为与__new__ class A方法兼容。

我被卡在__new__ class A __new__ class B方法的class B方法的部分,因为有很多初始化发生在那里,然后返回初始化的AutoIt实例。

我很难搞清楚这一点。请帮忙。

1 个答案:

答案 0 :(得分:2)

convert_param应为staticmethodclassmethod,您不希望从object.__new__致电B(否则,您就是实质上是尝试创建两个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的{​​{1}},以便不对从__new__返回的实例类型进行硬编码:

object.__new__