繁体   English   中英

多个 inheritance 在 python 2.7 中使用 Super(Subclass, self)

[英]Multiple inheritance using Super(Subclass, self) in python 2.7

我想了解 Python 2.7 中是否允许多个 inheritance 来自 class,其父级不是 ZA2669CFDE63931C499

Ref: TypeError in Python single inheritance with "super" 属性确实提供了一些示例,但我想使用 super(Subclass, self) 不同的方式,如下所示

动物 --> 哺乳动物 --> CannoFly & CannotSwim --> 狗

所以 Dog class 继承自 CannotFly 和 CannotSwim 类。 每个CannotFly 和CannotSwim class 都继承自Mammal,后者继承自Animal 类

    class Animal:
    def __init__(self, animalName):
        print(animalName, 'is an animal.');


# Mammal inherits Animal
class Mammal(Animal):
    def __init__(self, mammalName):
        print(mammalName, 'is a mammal.')
        super(Mammal,self).__init__(mammalName)


# CannotFly inherits Mammal
class CannotFly(Mammal):
    def __init__(self, mammalThatCantFly):
        print(mammalThatCantFly, "cannot fly.")
        super(CannotFly,self).__init__(mammalThatCantFly)


# CannotSwim inherits Mammal
class CannotSwim(Mammal):
    def __init__(self, mammalThatCantSwim):
        print(mammalThatCantSwim, "cannot swim.")
        super(CannotSwim,self).__init__(mammalThatCantSwim)


# Dog inherits CannotSwim and CannotFly
class Dog(CannotSwim, CannotFly):
    def __init__(self,arg):
        print("I am a barking dog")
        super(Dog, self).__init__(arg)



# Driver code
Dog1 = Dog('Bark')

当我运行它时,我收到错误“TypeError: must be type, not classobj”,这是因为 CanotSwim() 和 CannotFly() 类派生自 Mammal,它不是基础 class,而是继承自 Animal class。 如果不是这种情况,那么 Super(Subclass, self) 可以完美运行。

在 Python 2 中, super不适用于不(直接或间接)从object继承的对象。

旧式类允许使用多个 inheritance,但由于菱形问题可能会出现意外行为(请参阅此处的第 2.3 节)。

由于这些原因(以及许多其他原因),建议始终object 2 中的 object 继承。

暂无
暂无

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

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