python继承构造函数 python继承写法( 五 )


def age(self):
print "Grandfather age:"+str(self.a)
def sex(self):
print "Grandfather sex:"+str(self.s)
def Interesting(self):
print "Grandfather Interesting"
class Grandmother:
def __init__(self, age=70, sex="woman"):
self.a = age
self.s = sex
print "I am Grandmother"
def age(self):
print "Grandmother age:"+str(self.a)
def sex(self):
print "Grandmother sex:"+str(self.s)
def Interesting(self):
print "Grandmother Interesting"
class FatherWang(Grandfather, Grandmother):
def __init__(self, age=43, sex="man"):
self.a = age
self.s = sex
Grandfather.__init__(self, age, sex)
Grandmother.__init__(self, age, sex)
print "I am FatherWang"
def age(self):
print "Father age:"+str(self.a)
def sex(self):
print "Father sex:"+str(self.s)
class MotherLi(Grandfather, Grandmother):
def __init__(self, age=40, sex="woman"):
self.a = age
self.s = sex
Grandfather.__init__(self, age, sex)
Grandmother.__init__(self, age, sex)
print "I am MotherLi"
def age(self):
print "Mother age:"+str(self.a)
def sex(self):
print "Mother sex"+str(self.s)
def Interesting(self):
print "MotherLi Interesting"
class SonWang(FatherWang, MotherLi):
def __init__(self, age=13, sex="man"):
FatherWang.__init__(self, age, sex)
MotherLi.__init__(self, age, sex)
print "I am SonWang"
if __name__ == "__main__":
son = SonWang()
son.age()
son.sex()
son.Interesting()
执行结果:
I am Grandfather
I am Grandmother
I am FatherWang
I am Grandfather
I am Grandmother
I am MotherLi
I am SonWang
Father age:13
Father sex:man
Grandfather Interesting
话说,我自己都有点儿晕 。简单来讲,就是儿子继承了老爸、老妈,然后老爸继承了爷爷、奶奶 , 妈妈继承了老爷、姥姥 。(真是一大家子?。┩ü葱薪峁芍永嘞日业嚼习掷? ,然后再找老爸类的第1个父类爷爷类,此时发现爷爷类没有父类了 , 那么执行初始化 。然后还要继续找到老爸类的第2个父类奶奶类,此时发现奶奶类没有父类了,执行初始化 。此时老爸类的所有父类都初始化完成,初始化自己 。然后开始找妈妈类……那么为什么Interesting方法会使用爷爷类的呢?奶奶类、老爷类、姥姥类都有?。渴紫榷永嗝挥蠭nteresting方法,会先找第1个父类老爸类 。发现老爸类也没有,再找老爸类的第1个父类,发现找到了,那么就直接调用不再往下找了 。
结论:经典类的多继承,按照继承顺序查找 。即,从左到右,从下到上的方式 。注意,只有经典类是这样的!
(2).新式类的多继承:
class Grandfather(object):
def __init__(self, age=73, sex="man"):
self.a = age
self.s = sex
print "I am Grandfather"
def age(self):
print "Grandfather age:"+str(self.a)
def sex(self):
print "Grandfather sex:"+str(self.s)
def Interesting(self):
print "Grandfather Interesting"
class Grandmother(object):
def __init__(self, age=70, sex="woman"):
self.a = age
self.s = sex
print "I am Grandmother"
def age(self):
print "Grandmother age:"+str(self.a)
def sex(self):
print "Grandmother sex:"+str(self.s)
def Interesting(self):
print "Grandmother Interesting"
class FatherWang(Grandfather, Grandmother):
def __init__(self, age=43, sex="man"):
self.a = age
self.s = sex
Grandfather.__init__(self, age, sex)
Grandmother.__init__(self, age, sex)
print "I am FatherWang"
def age(self):
print "Father age:"+str(self.a)
def sex(self):
print "Father sex:"+str(self.s)

推荐阅读