0

Is that a pythonic way to create a class that inherits from more than 10 classes? Or maybe I should consider a different approach?

A.K.
  • 1
  • 1
  • Multiple inheritance is generally best avoided. 10 sounds excessive. Consider containment (ie members instantiated to some of these 10 classes). – Ron Kalian Dec 18 '17 at 14:22

4 Answers4

5

it is allowed, you can also consider creating a composite object, an object that has other objects as it's members, instead of inheriting them.

wiki for the concept of composition: composition

multiple inheritance in python: multiple inheritance

these should help you understand, and then decide what is better for you in the context of your program.

Avishay Cohen
  • 1,978
  • 2
  • 21
  • 34
2

Yes, inheriting from multiple classes in perfectly legal. However, if you have 10 super classes, it seems that you might need to tweak your inheritance tree. Perhaps some of the classes can be inherited by intermediate classes so that the final class inherits from fewer classes.

You should also learn about composition which might provide a cleaner solution for what you are trying to do.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

Multiple inheritance is valid in Python but not used often. Most of usecases that I seen is mixins (small snippets mixed into a main heirarchy tree).

Creating a class with 10 parents is a bad smell in any OOP language and not pythonic at all. You should refactor you classes into another kind of abstraction.

Arman Ordookhani
  • 6,031
  • 28
  • 41
0

Is that OK to inherit from many classes (more than 10) in Python?

It is "OK", in that Python will accept it and will not break or crash.

Is that a pythonic way to create a class or I should consider a different approach?

It is, most certainly, not a "pythonic" way to create a class. Having many parent classes only aggravates the well-known problems of having a few parent classes (diamond problem, etc.), plus it makes the class directly dependent on many others, and makes it very difficult to track down where each behavior in a class comes from. That goes against the general spirit of simplicity in Python (or good programming practices in general).

Note that making a class child of another one establishes an "is a" relationship. Is your class really all of those ten things? Or are you just inheriting to gain some of the already implemented behaviors? Look up some basic principles of object-oriented design such as SOLID, why sometimes we may prefer composition over inheritance, and alternative architectural patterns such as entity–component–system.

jdehesa
  • 58,456
  • 7
  • 77
  • 121