关于带参数的super()调用

class Metaclass (type):
    def donew(cls):
        print("+++ Metaclass: in donew--")
class MetaParams(Metaclass):
    def __new__(cls, *args, **kwargs):
        return type.__new__(cls,*args)
class Cerebro (object,metaclass= MetaParams):
    pass

if __name__ == '__main__':
    cerebro = Cerebro()
    print("Mro: ",Cerebro.__mro__)
    super(MetaParams, Cerebro).donew()

类Cerebro的MRO为:<class ‘main.Cerebro’>, <class ‘object’>
super(MetaParams, Cerebro):意思是按照Cerebro的MRO顺序寻找MetaParams的下一个,并返回,但是MRO中没有MetaParams,那么这个super返回的是哪个类。
试验表明super返回的是Metaclass这个类,但是为什么?

讨论数量: 2
Jason990420

Refer PEP 3135 – New Super

The new syntax:

super()

is equivalent to:

super(__class__, <firstarg>)

where

  • __class__ is the class that the method was defined in, and
  • <firstarg> is the first parameter of the method (normally self for instance methods, and cls for class methods).
super(MetaParams, Cerebro).donew()
>>> MetaParams.__mro__
(<class '__main__.MetaParams'>,
 <class '__main__.Metaclass'>,
 <class 'type'>,
 <class 'object'>)

super 只会从 MetaParams 之后查找,即: 只会在 Metaclass 或 type 或 object 中查找 donew 方法。

A “super instance” is simply an instance of the super class, which is associated with another class and possibly with an instance of that class.

>>> super(MetaParams, Cerebro)
<super: <class 'MetaParams'>, <MetaParams object>>
3周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!