0

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.

2

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @0x5453 very much for the reference , I understand the classic Diamond problem but what I'm unable to understand is was it allowed to have multiple inheritance from two classes which inherited from another class which inherited from another class /object. The reason is I can deal with the functional attribute/method overlook as in the Diamond problem but the code throws a run-time error and doesn't execute. Or simply I would be interested to understand best way to implement multiple inheritance in Python 2.7 for a common parent class , if at all it is possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.