I will explain the reason why the source code does not work.
Python must decide in which order to look for (direct and indirect) base classes when searching for an attribute / instance method. He does this by linearizing the inheritance graph, that is, by converting the base class graph into a sequence using an algorithm called C3 or MRO . The MRO algorithm is a unique algorithm that provides several desired properties:
- each class of ancestors appears exactly once
- a class always appears before its ancestor ("monotony")
- direct parents of the same class should be displayed in the same order as they are specified in the class definition ("consistent local priority order")
- if class
A children always appear in front of children of class B , then A should appear before B ("consistent extended priority order")
With your code, the second limitation requires Enemy appear first; the third limitation requires Player appear first. Since there is no way to satisfy all restrictions, python reports that your inheritance hierarchy is illegal.
Your code will work if you switch the order of the base classes in GameObject as follows:
class GameObject(Enemy, Player): pass
This is not just a technical detail. In some (hopefully rare) cases, you may need to think about which class should be used to capture the method that you called if the method is defined in several classes. The order in which you define the base classes affects this choice.
max 02 mar. '17 at 22:57 2017-03-02 22:57
source share