如何确定最接近的共同祖先类

时间:2013-04-03 13:29:51

标签: python inheritance lowest-common-ancestor

假设我有四个类:AB派生自AC派生自AD派生自C {1}}。 (所以我总是有单继承。) 在python中,确定任何两个(这类实例)类的最近共同祖先的最佳方法是什么?具体来说,我需要clcoancl(X,Y)clcoancl(A, B) == Aclcoancl(B, C) == A的函数clcoancl(C, D) == C

2 个答案:

答案 0 :(得分:3)

这适用于单个或多个继承,任意数量的类作为输入:

import inspect
from collections import defaultdict

def clcoancl(*cls_list):
    mros = [list(inspect.getmro(cls)) for cls in cls_list]
    track = defaultdict(int)
    while mros:
        for mro in mros:
            cur = mro.pop(0)
            track[cur] += 1
            if track[cur] == len(cls_list):
                return cur
            if len(mro) == 0:
                mros.remove(mro)
    return None # or raise, if that's more appropriate

正如NPE和Daniel Rossman所提到的那样,这可能不是解决根本问题的最佳方案。

答案 1 :(得分:2)

class A(object): pass
class B(A): pass
class C(A): pass
class D(C): pass

# get the list of ancestors (assuming single inheritance!)
def ancl(cls):
    ret = []
    while cls is not object:
        ret.append(cls)
        cls = cls.__bases__[0]
    ret.append(object)
    return ret

def clcoancl(cls1, cls2):
    ancl1 = ancl(cls1)
    ancl2 = ancl(cls2)
    # find the first class present in both ancl1 and ancl2
    while len(ancl1) > 0 and len(ancl2) > 0 and ancl1[-1] == ancl2[-1]:
        ret = ancl1.pop(-1)
        ancl2.pop(-1)
    return ret

print clcoancl(A, B)
print clcoancl(B, C)
print clcoancl(C, D)

你是否真的需要这个是另一回事,正如@DanielRoseman所指出的那样是他对你的问题的评论。