Metaclass multiple inheritance inconsistency

后端 未结 2 1928
[愿得一人]
[愿得一人] 2020-12-28 11:58

Why is this:

class MyType(type):
    def __init__(cls, name, bases, attrs):
        print \'created\', cls
class MyMixin:
    __metaclass__ = MyType
class My         


        
2条回答
  •  盖世英雄少女心
    2020-12-28 12:12

    It's not a custom-metaclass problem (though it's diagnosed at metaclass stage):

    >>> class Normal(object): pass
    ... 
    >>> class MyObject(object, Normal): pass
    ... 
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: Error when calling the metaclass bases
        Cannot create a consistent method resolution
    order (MRO) for bases object, Normal
    

    and the problem's just the same as this one:

    >>> class Derived(Normal): pass
    ... 
    >>> class Ok(Derived, Normal): pass
    ... 
    >>> class Nope(Normal, Derived): pass
    ... 
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: Error when calling the metaclass bases
        Cannot create a consistent method resolution
    order (MRO) for bases Normal, Derived
    

    i.e., can't multiply inherit from a base class followed by a derived class -- it's impossible to define a consistent MRO that satisfies the usual MRO constraints/guarantees.

    Fortunately, you don't want to do that -- the subclass presumably overrides some method of the base class (that's what normal subclasses do;-), and having the base class "in front" would mean "shadowing the override away".

    Putting the base class after the derived one is pretty useless, but at least it's innocuous (and consistent with normal MRO guarantees).

    Your first example of course works because MyMixin is not derived from list:

    >>> MyMixin.__mro__
    (, )
    

    ...but it is derived from object (like every modern-style Python class), so the second example cannot work (quite independently from MyMixin having a custom metaclass).

提交回复
热议问题