为什么__new__方法在超级方法中调用其父级__new__时需要传递cls参数?

NSD*_*ont 1 python super

我知道当我们通过super方法调用parent的方法时,我们可以忽略绑定方法中的"self"参数,如下所示:

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

__new__方法有所不同:

class Bar(object):
    def __new__(cls, *args, **kwargs):
        return super(Bar, cls).__new__(cls, *args, **kwargs) # Why need a "cls" argument?
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

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

__new__文档:

__new__() 是一个静态方法(特殊的,因此您不需要声明它),它将请求实例的类作为其第一个参数.

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

通常会在类型上查找具有双下划线的特殊方法,因此在类的元类上(type()默认情况下).这不适用,__new__因为你直接在类本身上声明了它.作为这种无描述符协议可以应用于任一(这是通常打开的功能成绑定的方法,为类和实例方法).因此,__new__钩子必须是特殊的,永远不会束缚.