、派生元、派生元A
、B
派生元の 4 つのクラスがあるとします。(だから私は常に単一の継承を持っています。) Python では、任意の 2 つの (そのようなインスタンスの) クラスの最も近い共通の祖先を決定する最良の方法は何ですか? 具体的には、 、、およびの関数が必要です。A
C
A
D
C
clcoancl(X,Y)
clcoancl(A, B) == A
clcoancl(B, C) == A
clcoancl(C, D) == C
1384 次
2 に答える
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 に答える