首页 > 解决方案 > 如果我们想强制调用父类方法,使用 Classname.method 名称而不是 super() 是唯一的解决方案吗?

问题描述

有什么方法可以确保在创建 B 的实例或 B 的任何子类的实例时,必须调用来自 A 的测试方法?

当前代码如下:

class A:
    def test(self):
        print(" test of A called ")
class B(A):
    def test(self):
        print(" test of B called ")
        super().test()
class C(A):
    def test(self):
        print(" test of C called ")
        #super().test()
class E(B):
    def test(self):
        print(" test of E called ")
        super().test()
class D(B,C):
    pass

obj1=B()
obj1.test()
print('xxxxxx')
obj3=E()
obj3.test()
print('xxxxxx')
obj2=D()
obj2.test()

输出:

B
A
xxxxxx
E
B
A
xxxxxx
B
C

如何在最后一种情况下确保 A 输出。将 B 类的测试方法更改为 A.test() 而不是 super().test() 是唯一的解决方案吗?

这意味着第三个输出将不再是 B、C,现在是 B、A。有没有办法保留 B、C、A?

标签: python

解决方案


您未能使用superinC.test会破坏最终导致A.test被调用的调用链。super支持协作继承,这意味着所有类都需要通过super一致的使用来协作。

class A:
    def test(self):
        print(" test of A called ")


class B(A):
    def test(self):
        print(" test of B called ")
        super().test()


class C(A):
    def test(self):
        print(" test of C called ")
        super().test()


class E(B):
    def test(self):
        print(" test of E called ")
        super().test()


class D(B,C):
    pass

现在,当您调用 时obj2.test(),您将从B.test(因为D.test未定义)开始。调用superinB.test导致C.test被调用,调用 inC.test将导致A.test被调用。


推荐阅读