gpt4 book ai didi

python - Mixin 覆盖继承的方法

转载 作者:行者123 更新时间:2023-11-28 22:38:27 27 4
gpt4 key购买 nike

我有一个类集合,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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com