python mro算法_python __mro__ c3算法 | 学步园

def mro_c3(*bases):

if len(bases) == 1:

if not bases[0].__bases__:

return bases

else:

return bases + mro_c3(*bases[0].__bases__)

else:

seqs = [list(mro_c3(C)) for C in bases] + [list(bases)]

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('adfadsf')

res.append(candidate)

for seq in non_empty:

if seq[0] == candidate:

del seq[0]

比如:

class A(object): pass

class B(dict ): pass

class CC(A, B): pass

求CC.__mro__步骤是:(下面mro既mro_c3)

(CC) + mro((A,B))

(CC)+[mro(A), mro(B)] + [[A, B]]

(CC) + [ (A, object),  (B, dict, object), [A,B]] ==> res =[]

(CC) + [ ( object),  (B, dict, object), [B]] ==> res =[A]

(CC) + [ (object),  (B, dict, object), [B]] ==> res =[A] #object 没有被加进res

(CC) + [ (object),  ( dict, object), []] ==> res =[A,B]

(CC) + [ (object),  ( dict, object)] ==> res =[A,B] #object 没有被加进res

(CC) + [ (object),  ( object)] ==> res =[A,B, dict]

(CC) + [ ] ==> res =[A,B, dict, object]

(CC) + res => (CC, A, B, dict, object)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值