繁体   English   中英

Python 将派生类合并到相同的基础 class?

[英]Python combine derived classes to the same base class?

假设我有一个基础 class Person和两个派生类FootballerMusician

显然一个人既可以是足球运动员也可以是音乐家,所以也许我想要第三个 class 称为FootballerAndMusician ,但是这个 class 将只是其他两个类的组合(不会有冲突:两个派生类只覆盖一些特定的东西,并且Musician中的任何内容都不会覆盖Footballer中覆盖的内容,反之亦然)。

在 Python 中实现此模式的适当方法是什么,以避免在第三个 class 中的两个派生类中重复代码(想象一下,如果我必须对多个类执行此操作……)?

基本上,我想为Person实现许多派生类,然后只要没有冲突就可以轻松地将它们组合起来。

这在 Python 中是如何设计的?

这称为多个 Inheritance,在 Python 中,它看起来像这样

class FootballerAndMusician(Footballer, Musician):
  # your specific class code goes here, like

现在 class 可以访问两个超类的所有方法。

查找方法的顺序有一些微妙的复杂性。 然而,在这个简单的例子中,它只是“从左到右”。 因此,如果FootballerMusician都有一个名为play的方法,那么在上面的示例中,您的FootballerAndMusician将使用Footballer版本。

请注意,多个 inheritance 会很快变得复杂和混乱,因此您应该谨慎使用它。 如果只是为了创建一些大的“分类法”,我建议避免使用它。

这很简单:

class FootballerAndMusician(Footballer, Musician):
    pass

当然,这假设FootballerMusician (以及Person )都被正确设计为允许多个 inheritance。 有关正确使用super的建议,请参阅https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

您正在寻找多个 inheritance。

Class Base1:
       (body_1)

Class Base2:
     (body_2)

Class Derived(Base1, Base2):
     (body_3)

只要您的 Base Class FootballerMusician不干扰其他人的方法,您就可以使用 go。
此外,如果您需要显式使用构造函数,

Class Derived(Base1, Base2):
    def __init__(self, args):
        super(Derived, self).__init__(args)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM