Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance in python vs composition [closed]

Tags:

python

I have a solid understanding of OOP and its idioms in Java.

Now I am coding in python, and I am in a situation where having multiple inheritance may be useful, however (and this may be due to years of java code), i am reluctant to do it and I am considering using composition instead of inheritance in order to avoid potential conflicts with potential equal method names.

Question is, am i being to strict or too java focused regarding this thing. Or using multiple inheritance in python is not only possible but also encouraged.

Thanks for your time :)

like image 307
Juan Antonio Gomez Moriano Avatar asked Feb 08 '12 04:02

Juan Antonio Gomez Moriano


2 Answers

The question of "inheritance vs. composition" comes down to an attempt to solve the problem of reusable code. You don't want to have duplicated code all over your code, since that's not clean and efficient. Inheritance solves this problem by creating a mechanism for you to have implied features in base classes. Composition solves this by giving you modules and the ability to simply call functions in other classes.

If both solutions solve the problem of reuse, then which one is appropriate in which situations? The answer is incredibly subjective, but I'll give you my three guidelines for when to do which:

  1. Avoid multiple inheritance at all costs, as it's too complex to be useful reliably. If you're stuck with it, then be prepared to know the class hierarchy and spend time finding where everything is coming from.
  2. Use composition to package up code into modules that is used in many different unrelated places and situations.
  3. Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept, or if you have to because of something you're using.

However, do not be a slave to these rules. The thing to remember about object oriented programming is that it is entirely a social convention programmers have created to package and share code. Because it's a social convention, but one that's codified in Python, you may be forced to avoid these rules because of the people you work with. In that case, find out how they use things and then just adapt to the situation.

More details can be found on: http://learnpythonthehardway.org/book/ex44.html

like image 86
Yasin Avatar answered Sep 30 '22 15:09

Yasin


I would still prefer composition to inheritance, whether multiple or single. Really getting into duck typing is a bit like having loads of implicit interfaces everywhere, so you don't even need inheritance (or abstract classes) very much at all in Python. But that's prefer composition, not never use inheritance. If inheritance (even multiple) is a good fit and composition isn't, then use inheritance.

like image 36
Ben Avatar answered Sep 30 '22 16:09

Ben