如何确定最接近的共同祖先类别 [英] How to determine the closest common ancestor class
问题描述
假设我有四个类:A
,从A
派生的B
,从A
派生的C
和从C
派生的D
. (因此,我始终具有单一继承.)
在python中,确定任何两个(此类实例)最接近的共同祖先的最佳方法是什么?具体来说,我需要一个clcoancl(X,Y)
,clcoancl(B, C) == A
和clcoancl(C, D) == C
的函数.
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 closest common ancestor of any two (instances of such) classes? Specifically, I need a function clcoancl(X,Y)
for which clcoancl(A, B) == A
, clcoancl(B, C) == A
, and clcoancl(C, D) == C
.
推荐答案
这应该适用于单继承或多继承,并可以输入任意数量的类:
This should work for single or multiple inheritance, with any number of classes as input:
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都提到的那样,这可能不是解决根本问题的最佳解决方案.
As both NPE and Daniel Rossman have mentioned though, this is probably not the optimal solution to your root problem.
这篇关于如何确定最接近的共同祖先类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!