如何用多重继承覆盖`__new__`?

时间:2017-07-19 14:39:52

标签: python new-operator multiple-inheritance

如何编写默认的__new__并进行一些小改动:

class A:
    def __new__(cls, *args, **kwargs):
        retval = super().__new__(cls, *args, **kwargs)
        retval.tree_parent = None
        return retval

class B(A):
    def __init__(self, x):
        self.x = x

b = B(1)

由于多态链中的其他类,我得到的错误是传递的参数不在此类的控件中:

TypeError: object() takes no parameters

1 个答案:

答案 0 :(得分:1)

默认__new__可以像在traitlets模块中一样编写:

def __new__(cls, *args, **kwargs):
    # This is needed because object.__new__ only accepts
    # the cls argument.
    new_meth = super(HasDescriptors, cls).__new__
    if new_meth is object.__new__:
        inst = new_meth(cls)
    else:
        inst = new_meth(cls, *args, **kwargs)
    # Do something with inst.
    return inst