Python多重继承/混合

标签 python multiple-inheritance

我有以下问题:

class A:
    animal = 'gerbil'

    def __init__(self):
        self.result = self.calculate_animal()

    def calculate_animal(self):
        print(self.animal)
        return self.animal

class B(A):
    animal = 'zebra'

    def __init__(self):
        super(B, self).__init__()

现在,我想要 A 的一组特定子类,以实现一个新函数来计算与动物不同的东西,如下所示:

class CapitalizeAnimal:

    def calculate_animal(self):
        self.animal = self.animal.upper()
        # I need to call some version of super().self.animal,
        # but how will this Mixin class know of class A?


class C(A, #CapitalizeAnimal?):
    animal = 'puma':

    def __init__(self):
        super(C, self).__init__()

如何让 C 类 实现 calculate_animalCapitalizeAnimal 版本,同时保持其动物为 puma?我对 Mixin 类如何调用 super() 函数感到困惑。

最佳答案

父类的顺序很重要,你应该这样做:

class C(CapitalizeAnimal, A):
     animal = 'puma'

     def __init__(self):
         super(C, self).__init__()

更多信息可以通过阅读 MRO 找到。 (方法解析顺序)。


此外,super 仅适用于 new style classes ,所以你应该让 A 继承 object (当然除非你使用的是 Python 3)。

关于Python多重继承/混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126376/

相关文章:

python - 你怎么知道github存储库是用于python 2还是python 3

python - 将字典和变量列表插入表中

c++ - gzstream lib打开不存在的文件

javascript - 如何在 Javascript 中测试多重继承

c++ - 如何让 Doxygen 显示菱形继承图

python - 查找 pandas DataFrame 值的索引

python - while 循环和 python

Python gui - 将输入传递给脚本

python:基类中的多重继承和__add__()

python - 如何处理多个不合作的 API 类并使它们合作?