gpt4 book ai didi

python - 为什么 __new__ 方法在跨 super 方法调用其父级的 __new__ 时需要传递 cls 参数?

转载 作者:行者123 更新时间:2023-12-03 20:37:03 24 4
gpt4 key购买 nike

我知道当我们通过 super 方法调用父方法时,我们可以忽略绑定(bind)方法中的“self”参数,如下所示:

class Foo(object):
def __init__(self):
super(Foo, self).__init__() # We needn't pass in the "self" argument
# ...

但是 __new__ 的情况有所不同方法:
class Bar(object):
def __new__(cls, *args, **kwargs):
return super(Bar, cls).__new__(cls, *args, **kwargs) # Why need a "cls" argument?

最佳答案

__new__不是实例方法;它是一个传递给类对象的静态方法(也使它不是一个类方法)。

来自 __new__ documentation :

__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument.



因此,即使使用 super()查找下一个 __new__ MRO 中的方法,你仍然需要传入 cls明确地。

带有双下划线的特殊方法通常在类型上查找,因此在类的元类上(默认为 type())。这对 __new__ 不起作用因为您直接在类本身上声明了它。因此没有 descriptor protocol也可以应用(对于类和实例方法,这通常会将函数转换为绑定(bind)方法)。因此 __new__ hook 必须是特殊的,并且永远不会被绑定(bind)。

关于python - 为什么 __new__ 方法在跨 super 方法调用其父级的 __new__ 时需要传递 cls 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19973209/

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