I come from the Java background, but I am sure that the same principles apply to Python. As a rule, you should never inherit from a class whose implementation you do not understand and do not control, unless this class has been specifically designed for inheritance. If it was designed in this way, it should clearly describe it in its documentation.
The reason for this is that inheritance can potentially connect you with the implementation details of the class you inherit from.
To use an example from Josh Bloch’s book, Effective Java
If we extended the ArrayList class to be able to count the number of elements that were added to it during its life cycle (not necessarily the number it currently contains), we might be tempted to write something like this.
public class CountingList extends ArrayList { int counter = 0; public void add(Object o) { counter++; super.add(0); } public void addAll(Collection c) { count += c.size(); super.addAll(c); }
Now this extension looks like it will accurately count the number of items that have been added to the list, but in reality this may not be the case. If ArrayList implemented addAll by iterating over the provided Collection and calling its addAll interface addAll for each element, we will count each element added through the addAll method twice. Now the behavior of our class depends on the implementation details of ArrayList .
This, of course, is in addition to the inability to use other List implementations with our CountingList class. Plus the disadvantages of inheriting from a particular class, which are discussed above.
I understand that Python uses a similar (if not identical) method to submit a Java method and therefore will be subject to the same restrictions. If anyone could provide an example in Python, I am sure it will be even more useful.
Francis stephens
source share