读书人

多重继承有关问题

发布时间: 2012-02-04 15:43:09 作者: rapoo

多重继承问题?
#! /usr/bin/env python
#coding=utf-8
class P1(object): # parent class 1 父类1
def foo(self):
print 'called P1-foo()'

class P2(object): # parent class 2 父类2
def foo(self):
print 'called P2-foo()'

def bar(self):
print 'called P2-bar()'

class C1(P1, P2): # child 1 der. from P1, P2 #子类1,从P1,P2派生
pass

class C2(P1, P2): # child 2 der. from P1, P2 #子类2,从P1,P2派生
def bar(self):
print 'called C2-bar()'

class GC(P1, C1): # define grandchild class #定义子孙类
pass # derived from C1 and C2 #从C1,C2派生

print GC.__bases__
为什么GC(P1,C1)会出错?

[解决办法]
class GC( P1, C1):
pass

如果这样的话,mro 的 记录就会变成
GC -> P1 -> C2 -> P1 -> ...
其中P1的下一个是谁?不确定, 会出错


如果把他便成
class GC(C1, P1):
pass

mro 的 记录就会变成
GC -> C1 -> P1 -> P2 -> Object
很正常喔

读书人网 >perl python

热点推荐