Mixin 覆盖继承的方法

Mixin to override inherited method

我有一个 classes、A1、A2、A3 等的集合,它们都有方法 m()。我还有 class B 方法 m()。我希望能够轻松地创建 classes C1、C2、C3 等,它们从 class B 调用 m(),同时还具有 A1、A2、A3 等的所有其他属性。 ..

但是,我遇到的问题是,在 class C1 中,来自 class B 的方法 m() 应该从 class A1.

我很难用语言表达我想要的东西,但我目前正在考虑这样做的方式是使用 mixins。 C1 将从 A1 继承,混合 B。但是,我不知道如何使 B 中的 m() 从 A classes 之一调用正确的 m() .

那么,我的两个问题:

编辑:根据要求,一个具体的例子: A1、A2、A3等中的方法m(p)都计算了一个矩阵M,对于一些参数p。我想创建 classes C1、C2、C3 等,它们的行为方式与 A1、A2、A3 相同, 除了 方法 m()。新方法 m() 采用更长的参数列表 p,大小为 N,我们计算 A*.m() N 次,然后 return 总和。

计算 m() 总和的代码对于所有 A* class 都是相同的。在上面建议的混合解决方案中,求和代码将在 B 中。B 和 A1 将被继承以形成 C1。但是,B 中 C1 中的方法 m() 必须调用 A1.m().

我认为您只需要 super 即可将调用重定向到 parent 或同级 class(取决于 MRO)。

例如:

class A1(object):
    def m(self):
        print('Calling method m of class A1')
        self.data *= 2

class A2(object):
    def m(self):
        print('Calling method m of class A2')
        self.data *= 3

class A3(object):
    def m(self):
        print('Calling method m of class A3')
        self.data *= 4

class B(object):
    def m(self, p):
        print('Calling method m of class B')
        for i in range(p):
            # You haven't specified which python you are using so I assume
            # you might need to most explicit variant of super().
            # Python3 also allows just using super().m()
            super(B, self).m()

class C1(B, A1):
    def __init__(self, value):
        self.data = value

正在测试:

a = C1(10)
a.m(10)

打印:

Calling method m of class B
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1
Calling method m of class A1

和保存的值:

a.data
# returns 10485760

定义其他 C 也有效:

class C2(B, A2):
    def __init__(self, value):
        self.data = value

a = C2(10).m(2)
#Calling method m of class B
#Calling method m of class A2
#Calling method m of class A2


class C3(B, A3):
    def __init__(self, value):
        self.data = value

a = C3(10).m(1)
#Calling method m of class B
#Calling method m of class A3

当然你想要另一个逻辑并且可能需要 return 来自 .m() 的值而不是修改 in-place 但我认为你可以自己解决它们。

您要查找的词可能是 MRO (method resolution order)。希望对你有帮助。

super (Python2), super (Python3) 的文档也很有趣。

并且您始终可以通过调用 .mro() 方法来检查 class 的 MRO

print(C1.mro())
[<class '__main__.C1'>, <class '__main__.B'>, <class '__main__.A1'>, <class 'object'>]

所以 python 首先检查 C1 是否有方法 m,如果没有则检查 BB 有一个所以它被执行了。 super 调用然后再次进入 MRO 并检查下一个 class (A1) 是否有方法 m,然后执行。