gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:54 26 4
gpt4 key购买 nike

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

最佳答案

默认的__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

关于python - 如何使用多重继承覆盖 `__new__`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com