我一直在搞Python的黑暗藝術,並有一些我想幫助理解。鑑於一類Foo
,這裏的某些方面,我試圖從它繼承:提供Foo
Metaclass衝突,多繼承和實例作爲父
class A(Foo)
—作品,unsurprizinglyclass B(Foo())
—作品具有適當__new__
方法(我公司提供)class C(Foo(), Foo)
—作品,在與B
相同的條件下class D(Foo, Foo())
—給出了着名的元類e rror:Traceback (most recent call last):
File "test.py", line 59, in
class D(Foo, Foo()):
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
What exactly is it that causes this conflict? When I inherit from (Foo(), Foo)
(instance first, class second) it works, but when I inherit from (Foo, Foo())
(class first, instance second), it doesn't.
你說得對。順便說一下,「MRO訂單」是什麼意思? –
@Paul MRO是「方法解析順序」,它是在查找方法/屬性時檢查類及其父項的順序。我的直覺就是,因爲第一個父代中的方法'重寫'了第二個中的方法,Python會處理第二個,然後處理第一個。 – Ben