如何编写默认的__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
答案 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