gpt4 book ai didi

python - 在多重继承的情况下, super 方法如何在 python 中工作?

转载 作者:太空狗 更新时间:2023-10-29 21:08:40 24 4
gpt4 key购买 nike

super 方法在 python 中如何实际工作?

在给定的代码中:

class A(object):
def test(self):
return 'A'


class B(A):
def test(self):
return 'B->'+super(B, self).test()


class C(A):
def test(self):
return 'C'


class D(B,C):
pass


print B().test() # B->A
print D().test() # B->C ????

# MRO of classes are as
print 'mro of A', A.__mro__ # [A,object]
print 'mro of B', B.__mro__ # [B,A,object]
print 'mro of C', C.__mro__ # [C,A,object]
print 'mro of D', D.__mro__ # [D,B,C,A,object]

当在 D 上调用 test 时,它输出 B->C 而不是 B->A(这是我所期望的)。

B 中的 super 是如何引用 C 的实例的?

最佳答案

来自文档:

super(type[, object-or-type]): Return a proxy object that delegates method calls to a parent or sibling class of type

强调我的。

MRO(如您打印出来的那样)确定方法解析顺序,在本例中为(D、B、C、A、对象)。因此,super(B, self)D 中调用时返回一个代理对象,该对象将根据 MRO 将方法委托(delegate)给其兄弟 C .

这实际上可以用于在不修改现有类的情况下扩展继承层次结构中的行为。请注意,B 实际上不知道它的 test() 方法将被分派(dispatch)到哪个类——它只是使用一个间接的 super() 调用。您只需创建一个按所需顺序混合多个基类的新类,即可在 MRO 中插入不同的类。

例如,假设您的原始层次结构仅包含类 ABD。假设,稍后您需要使用日志记录检测所有 B 的方法调用。无需修改 B,您可以简单地创建一个新类 C 来执行日志记录并让 D 继承 C,因此将它插入到 B 之后的 MRO 中。

关于python - 在多重继承的情况下, super 方法如何在 python 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22879433/

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