Python 超级覆盖对象名称

Python super override object name

我正在尝试扩展一个框架,我有这样的东西:

class A(object):
    def test(self):
        print(1)


class B(object):
    def method(self):
        a = A()
        a.test()


class CustomA(A):
    def test(self):
        print(2)


class C(B):

    def method(self):
        A = CustomA
        super(C, self).method()

c = C()
c.method()

类A、B来自框架

我想从 A 编辑这个 test(),让 C 使用这个新方法。

例如,在这段代码中,如何让我的代码打印 2 而不是 1?

[更新]

这只是一个简单的例子。我想延长 this class。因此,与其创建 SettingsPanel,不如创建 CustomSettingsPanel

但问题是我需要用很多 类 来做,所以我只想要一种方法让 python 总是使用 CustomSettingsPanel 而不是 SettingsPanel.

您不需要在 C 中调用 super。您正在尝试覆盖 B 的方法。

class A(object):
    def test(self):
        print(1)


class B(object):
    def method(self):
        a = A()
        a.test()


class CustomA(A):
    def test(self):
        print(2)


class C(B):
    def method(self):
        A = CustomA()
        A.test()

c = C()
c.method()

有很多方法可以解决这个问题。

如果你可以编辑 B,那么你可以重构它,而不是对 A 的硬依赖,让它接受 ___init___ 中的一个参数以允许一个人指定 class 进行实例化。类似于:

class B(object):
    def __init___(self, clazz=A):
        self.__clazz = clazz
    def method(self):
        a = self.__clazz()
        a.test()

class C(B):
    def __init__(self):
        super(C, self).__init__(CustomA)

如果您无法编辑 B,那么我建议将其包装在适配器中,让您的代码通过 class(而不是 BC),然后通过标志参数在适配器中管理 ACustomA 选择的复杂性:

class ABCAdapter(object):
    USE_CLASS_A = 0
    USE_CLASS_CUSTOMA = 1

    def __init__(self, test_class=USE_CLASS_A):
        if test_class = USE_CLASS_A:
            self.a_instance = A()
        elif test_class = USE_CLASS_CUSTOMA:
            self.a_instance = CustomA()

    def method(self):
        self.a_instance.test()

还可以研究其他对象创建模式(工厂等)。一切都取决于您的限制和您想要完成的目标。