gpt4 book ai didi

python - 如何在 Python 中从 `super()` 获取实例方法的下一个父类

转载 作者:太空狗 更新时间:2023-10-30 02:43:49 25 4
gpt4 key购买 nike

我想知道从 super() 函数获得的实​​例的类型。我尝试了 print(super())__print(type(super()))__

class Base:
def __init__(self):
pass

class Derive(Base):
def __init__(self):
print(super())
print(type(super()))
super().__init__()

d = Derive()

结果是

<super: <class 'Derive'>, <Derive object>>
<class 'super'>

有了这些结果,我想知道 super().__init__() 是如何调用正确的构造函数的。

最佳答案

你不能直接用 super() 做你想做的事。转到类 MRO(请参阅 class.__mro__):

class Derive(Base):
def __init__(self):
mro = type(self).__mro__
parent = mro[mro.index(__class__) + 1]
print(parent)

这里的 __class__ 是神奇的闭包变量*,它引用了定义当前函数的类;即使您使用 Derive 子类化或混合其他类,即使您生成了菱形继承模式,上述内容仍然有效。

演示:

>>> class Base: pass
...
>>> class Derive(Base):
... def __init__(self):
... mro = type(self).__mro__
... parent = mro[mro.index(__class__) + 1]
... print(parent)
...
>>> Derive()
<class '__main__.Base'>
<__main__.Derive object at 0x10f7476a0>
>>> class Mixin(Base): pass
...
>>> class Multiple(Derive, Mixin): pass
...
>>> Multiple()
<class '__main__.Mixin'>
<__main__.Multiple object at 0x10f747ba8>

注意 Multiple 类是如何继承自 DeriveMixin 的,因此 MRO 中的下一个类是 Mixin不是Base,因为Mixin派生自Base >.

这复制了 super() 所做的;在实例的 MRO 中找到下一个类,相对于当前类。


* 有关背景,请参阅 Why is Python 3.x's super() magic?

关于python - 如何在 Python 中从 `super()` 获取实例方法的下一个父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014260/

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