Python中super()调用输出的__init__ method-wrapper含义是什么
Python super()调用中method-wrapper类型的含义解释
super()基础定义
super() 会返回一个超类实例,该实例会跟踪MRO(方法解析顺序)中的当前位置。在super实例上调用方法时,super会查找MRO中的下一个类,并调用该类上的对应方法。
测试代码
class mon(): def __init__(self): print("i am in mon's init") print(super()) print(super().__init__) super().__init__() class far(): def __init__(self): print("i am in far's init") print(super()) print(super().__init__) super().__init__() class son(mon,far): def __init__(self): print("i am in son's init") print(super()) print(super().__init__) super().__init__()
son类的MRO输出
son.__mro__ # 输出:(<class '__main__.son'>, <class '__main__.mon'>, <class '__main__.far'>, <class 'object'>)
son类实例化的输出
x = son() # 输出: # i am in son's init # <super: <class 'son'>, <son object>> # <bound method mon.__init__ of <__main__.son object at 0x7ff0376f5c70>> # i am in mon's init # <super: <class 'mon'>, <son object>> # <bound method far.__init__ of <__main__.son object at 0x7ff0376f5c70>> # i am in far's init # <super: <class 'far'>, <son object>> # <method-wrapper '__init__' of son object at 0x7ff0376f5c70>
疑问解答
你观察到的现象完全符合super()的调用规则,不存在不符合规律的情况,相关说明如下:
- far类中的
super().__init__确实指向MRO中下一个类object的__init__方法,你看到的method-wrapper是Python对内置C实现方法的包装类型:普通用Python语法定义的类方法绑定实例后,打印会显示bound method 类名.方法名的格式;而object是Python底层用C实现的内置基类,它的__init__方法绑定到Python实例后,打印就会显示method-wrapper格式,这和你预期的object.__init__是同一个东西,只是显示形式不同。 - 这个
method-wrapper完全不会指向son类的__init__,自然不会出现循环调用重复打印的情况:super查找方法的规则是从MRO序列中当前类的下一个位置往后查找,far类在MRO序列中的位置之后只有object,所以只会找到object.__init__,不会往前匹配son类的方法。
内容的提问来源于stack exchange,提问作者showkey
相关产品推荐
相关产品推荐

