python - Mixin 覆盖继承的方法

标签 python inheritance multiple-inheritance mixins

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

但是,我遇到的问题是,在 C1 类中,B 类的方法 m() 应该调用 A1 类的 m()

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

那么,我的两个问题:

  • 我想做的事情有名字吗?
  • 执行此操作的正确方法是什么?

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

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

最佳答案

我认为您只需要 super 即可将调用重定向到父类或兄弟类(取决于 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

当然,您需要另一个逻辑并且可能需要从 .m() 返回值而不是就地修改,但我认为您可以自己解决。

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

同样感兴趣的可能是 super (Python2) 的文档。 , super (Python3) .

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

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

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

关于python - Mixin 覆盖继承的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561346/

相关文章:

python - Pandas 将带有方括号的列作为字符串而不是列表导入

子类的 C++ 静态成员修饰符

c++ - 派生类构造函数初始化列表中的多重继承和继承数据成员

c++ - 多重继承和数据成员

python - 按变量 pandas 过滤

javascript - 如何将JS日期字符串转换为django日期时间格式?

python:子类元类

java - 从指向专用类型实例的类类型变量进行部分访问

Java 反射 getConstructor 方法

java - Java 中的多重继承是如何工作的?