钻石继承的MRO问题? [英] MRO problems with diamond inheritance?
问题描述
试图创造不平衡的钻石。继承如下:
Trying to create the "lopsided diamond" inheritance below:
B类(对象):传递
类D1(B):传递<类D2(D1):传递
D类(D1,D2):传递
回溯(最近一次调用最后一次):
文件"< stdin> ",第1行,在?
TypeError:调用元类库时出错
无法创建一致的方法解析
order(MRO)对于基地D1,D2
这是按预期的吗?特别是因为撤销订单就可以了:
D级(D2,D1):传递
D .__ mro __
class B(object):pass
class D1(B):pass
class D2(D1):pass
class D(D1, D2):pass Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases D1, D2
Is this as intended? Especially since reversing the order makes it OK:
class D(D2, D1):pass
D.__mro__
(< class''__ main __。D''>,< class''__ main __。D2''>,< class''_ _ main __。D1''>,
< class''__ m
ain __。B''>,< type''object''>)
为什么要订购基类重要吗?这仅影响类型,
旧式类不受影响。
此问题的解决方法(如果是问题而不是功能>
,我误解了)是将更多派生的类放在列表的前面
。我使用动态创建的类遇到了这个,并且使用以下比较器对基本列表进行排序,将它们放错:
def cmpMRO(x,y) :
如果x == y:
返回0
elif issubclass(x,y):
返回-1
elif issubclass(y,x):
返回+1
否则:
返回cmp( id(x),id(y))
顺便说一句,在类中使用mro()方法是安全的,或者这是
as保留为通常的__reserved_words__? Python是否在内部或任何地方使用mro()(因为
反对__mro__)?
谢谢
John
(<class ''__main__.D''>, <class ''__main__.D2''>, <class ''__main__.D1''>,
<class ''__m
ain__.B''>, <type ''object''>)
Why should order of base classes matter? This only affects types,
old-style classes are unaffected.
The workaround to this problem (if it is a problem and not a feature
that I''m misunderstanding) is to put more-derived classes at the front
of the list. I ran into this with dynamically-created classes, and
sorting the bases list with the following comparator put them right:
def cmpMRO(x,y):
if x == y:
return 0
elif issubclass(x, y):
return -1
elif issubclass(y, x):
return +1
else:
return cmp(id(x), id(y))
Incidentally, is it safe to have an mro() method in a class, or is this
as reserved as the usual __reserved_words__? Does Python use mro() (as
opposed to __mro__) internally or anything?
Thanks
John
推荐答案
你的答案就在这个页面的某个地方;)
http://www.python.org/2.2.2/descrintro.html
MEFarmer
Your answer lies somewhere in this page ;)
http://www.python.org/2.2.2/descrintro.html
M.E.Farmer
MEFarmer:
你的答案就在这个页面的某个地方;)
http://www.python.org/2.2.2/descrintro.html
MEFarmer
Your answer lies somewhere in this page ;)
http://www.python.org/2.2.2/descrintro.html
M.E.Farmer
delegate.py(使用PyPI)也可能有用。
-Robert Dick -
delegate.py (use PyPI) may also be useful.
-Robert Dick-
> MEFarmer:
> M.E.Farmer:
你的答案就在这个页面的某个地方;)
http://www.python.org/2.2.2/de*scrintro.html
Your answer lies somewhere in this page ;)
http://www.python.org/2.2.2/de*scrintro.html
是的,当它引用时
http ://www.python.org/2.3/mro.html
(不良方法解决方案订单部分)。
简而言之,这是一个功能,而不是一个bug。
Michele Simionato
Yes, when it refers to
http://www.python.org/2.3/mro.html
(section Bad Method Resolution Orders).
In short, it is a feature, not a bug.
Michele Simionato
这篇关于钻石继承的MRO问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!