How To Determine The Closest Common Ancestor Class
Suppose I have four classes: A, B derived from A, C derived from A, and D derived from C. (So I always have single inheritance.) In python, what is the best way to determine the cl
Solution 1:
This should work for single or multiple inheritance, with any number of classes as input:
import inspect
from collections import defaultdict
defclcoancl(*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] += 1if track[cur] == len(cls_list):
return cur
iflen(mro) == 0:
mros.remove(mro)
returnNone# or raise, if that's more appropriate
As both NPE and Daniel Rossman have mentioned though, this is probably not the optimal solution to your root problem.
Solution 2:
classA(object): passclassB(A): passclassC(A): passclassD(C): pass# get the list of ancestors (assuming single inheritance!)defancl(cls):
ret = []
while cls isnotobject:
ret.append(cls)
cls = cls.__bases__[0]
ret.append(object)
return ret
defclcoancl(cls1, cls2):
ancl1 = ancl(cls1)
ancl2 = ancl(cls2)
# find the first class present in both ancl1 and ancl2whilelen(ancl1) > 0andlen(ancl2) > 0and 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)
Whether you actually need this is a different matter, as pointed out by @DanielRoseman is his comment to your question.
Post a Comment for "How To Determine The Closest Common Ancestor Class"