python mro算法_Python MRO C3算法实现

算法实现

#-*- encoding:GBK -*-#

def mro_C3(*cls):

if len(cls)==1:

if not cls[0].__bases__:

return cls

else:

return cls+ mro_C3(*cls[0].__bases__)

else:

seqs = [list(mro_C3(C)) for C in cls ] +[list(cls)]

res = []

while True:

non_empty = list(filter(None, seqs))

if not non_empty:

return tuple(res)

for seq in non_empty:

candidate = seq[0]

not_head = [s for s in non_empty if candidate in s[1:]]

if not_head:

candidate = None

else:

break

if not candidate:

raise TypeError("inconsistent hierarchy, no C3 MRO is possible")

res.append(candidate)

for seq in non_empty:

if seq[0] == candidate:

del seq[0]

测试一

#####################测试1

ob=object

class A(ob):

pass

class B(ob):

pass

class X(A,B):

pass

class Y(A,B):

pass

try:

class Z(X,Y):

pass

print Z.mro()

print Z.__mro__

print mro_C3(Z)

except :pass

try:

print mro_C3(X,Y)#如果从X,Y继承,它的MRO值是什么

except Exception,e:

print e

######打印结果

[, , , , , ]

(, , , , , )

(, , , , , )

(, , , , )

测试二

#####################测试2

ob=object

class A(ob):

pass

class B(ob):

pass

class X(A):

pass

class Y(B):

pass

try:

class Z(X,Y):

pass

print Z.mro()

print Z.__mro__

print mro_C3(Z)

except :pass

try:

print mro_C3(X,Y)#如果从A,B继承,它的MRO值是什么

except Exception,e:

print e

####打印结果

[, , , , , ]

(, , , , , )

(, , , , , )

(, , , , )

测试三

#####################测试3

ob=object

class A(ob):

pass

class B(ob):

pass

class X(A,B):

pass

class Y(B,A):

pass

try:

class Z(X,Y):

pass

print Z.mro()

print Z.__mro__

print mro_C3(Z)

except :pass

try:

print mro_C3(X,Y)#如果从A,B继承,它的MRO值是什么

except Exception,e:

print e

##打印结果 报错了,无法 定义 类 Z

inconsistent hierarchy, no C3 MRO is possible

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-08-26 11:24

浏览 1752

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值