2

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

4

2 回答 2

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 所提到的,这可能不是解决根本问题的最佳解决方案。

于 2013-04-03T13:55:47.913 回答
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 指出的那样,您是否真的需要这是另一回事,这是他对您问题的评论。

于 2013-04-03T13:40:56.310 回答