简体   繁体   English

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

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

I'd like to understand if multiple inheritance is allowed in Python 2.7 from a class whose parent is not an object?我想了解 Python 2.7 中是否允许多个 inheritance 来自 class,其父级不是 ZA2669CFDE63931C499

Ref: TypeError in Python single inheritance with "super" attribute do provide some examples but I'd like to use super(Subclass, self) differently as below Ref: TypeError in Python single inheritance with "super" 属性确实提供了一些示例,但我想使用 super(Subclass, self) 不同的方式,如下所示

Animal --> Mammal --> CannoFly & CannotSwim --> Dog动物 --> 哺乳动物 --> CannoFly & CannotSwim --> 狗

So Dog class inherits from CannotFly and CannotSwim classes.所以 Dog class 继承自 CannotFly 和 CannotSwim 类。 Each of the CannotFly and CannotSwim class inherits from Mammal which inherit from Animal classes每个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')

When I run it I get the error "TypeError: must be type, not classobj" which is because the CanotSwim() & CannotFly() classes are derived from Mammal which is not the base class but inheriting from Animal class.当我运行它时,我收到错误“TypeError: must be type, not classobj”,这是因为 CanotSwim() 和 CannotFly() 类派生自 Mammal,它不是基础 class,而是继承自 Animal class。 If that was not the case, then the Super(Subclass, self) works perfectly.如果不是这种情况,那么 Super(Subclass, self) 可以完美运行。

In Python 2, super does not work with objects that don't inherit (directly or indirectly) from object .在 Python 2 中, super不适用于不(直接或间接)从object继承的对象。

Multiple inheritance is allowed with old-style classes, but may have unexpected behavior due to the Diamond Problem (see section 2.3 here ).旧式类允许使用多个 inheritance,但由于菱形问题可能会出现意外行为(请参阅此处的第 2.3 节)。

For these reasons (and many others) it is recommended to always inherit from object in Python 2.由于这些原因(以及许多其他原因),建议始终object 2 中的 object 继承。

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

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