Python超级重写对象名

Python超级重写对象名,python,inheritance,overriding,super,Python,Inheritance,Overriding,Super,我试图扩展一个框架,我有这样的东西: 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

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

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

[更新]


这只是一个简单的例子。我想延长。因此,不要创建一个
设置span
,而是创建一个
自定义设置span


但问题是,我需要用很多类来实现这一点,所以我只想找到一种方法,使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
进行硬依赖,而是接受
\uuuuuuuuu init\uuuuuuuu
中的一个参数,以允许指定要实例化的类。比如:

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
,那么我建议将其包装在适配器中,让您的代码通过该类进行交互(而不是
B
C
),然后通过标志参数管理适配器中
A
CustomA
选择的复杂性:

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()

还可以研究其他对象创建模式(工厂等)。这一切都取决于您的约束条件和您要完成的任务。

这只是一个简单的示例。我想延长。因此,与其创建一个
SettingsPanel
,不如创建一个
customsetingspanel
,但问题是我需要用很多类来完成,所以我只想找到一种方法,让python始终使用
customsetingspanel
,而不是
setingspanel
。为什么你不能只创建
customsetingspanel
,然后重构代码以使用它而不是
SettingsPanel
?我做了,但是有很多kivy类使用
SettingsPanel
。因此,为了让每个类都使用
CustomSettingsPanel
,而不是Kivy default,我需要继承每个类并编辑所需的方法。所以我的代码很大,只是为了使用这个自定义类。