Reputation: 1
I'd like to understand if multiple inheritance is allowed in Python 2.7 from a class whose parent is not an object ?
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
Animal --> Mammal --> CannoFly & CannotSwim --> Dog
So Dog class inherits from CannotFly and CannotSwim classes. Each of the CannotFly and CannotSwim class inherits from Mammal which inherit from Animal classes
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. If that was not the case, then the Super(Subclass, self) works perfectly.
Upvotes: 0
Views: 260
Reputation: 13589
In Python 2, super
does not work with objects that don't inherit (directly or indirectly) from object
.
Multiple inheritance is allowed with old-style classes, but may have unexpected behavior due to the Diamond Problem (see section 2.3 here).
For these reasons (and many others) it is recommended to always inherit from object
in Python 2.
Upvotes: 1