面试题之一。
class Parent(object):
x = 1
class Child1(Parent):
pass
class Child2(Parent):
pass
print "Parent.x = ",Parent.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Child1.x = 2
print "Parent.x = ",Parent.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Parent.x = 3
print "Parent.x = ",Parent.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
结果是:
Parent.x = 1 Child1.x = 1 Child2.x = 1
Parent.x = 1 Child1.x = 2 Child2.x = 1
Parent.x = 3 Child1.x = 2 Child2.x = 3
这道题终于做对了,因为记得,当派生类找不到对应的方法or属性时,会到基类那里去找。
而且是找最近的一个有这个属性的爸爸(爸爸去哪了)。
class GrandFather(object):
x = 100
y = 99
class Parent(GrandFather):
x = 1
class Child1(Parent):
pass
class Child2(Parent):
pass
print "Parent.x = ",Parent.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Child1.x = 2
print "Parent.x = ",Parent.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Parent.x = 3
print "Parent.x = ",Parent.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
print "Parent.y = ",Parent.y,"Child1.y = ",Child1.y,"Child2.y = ",Child2.y
结果先预测下,因为Parent已经有x了,所以Child1和Child2就找到Parent.x即可。
但是连Parent都没有y,所以Child1和Child2必须到GrandFather那里去才找到y属性。
结果:
Parent.x = 1 Child1.x = 1 Child2.x = 1
Parent.x = 1 Child1.x = 2 Child2.x = 1
Parent.x = 3 Child1.x = 2 Child2.x = 3
Parent.y = 99 Child1.y = 99 Child2.y = 99
咦,上面的是单继承,很简单的关系,万一是多继承呢,看看下面的孩子到底是随爸爸还是随妈妈?
class People(object):
x = 100
y = 99
class Father(People):
x = 11
class Mother(People):
x = 22
class Child1(Father,Mother):
pass
class Child2(Father,Mother):
pass
print "Father.x = ",Father.x,"Mother.x = ",Mother.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Child1.x = 2
print "Father.x = ",Father.x,"Mother.x = ",Mother.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Father.x = 33
print "Father.x = ",Father.x,"Mother.x = ",Mother.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
Mother.x = 44
print "Father.x = ",Father.x,"Mother.x = ",Mother.x,"Child1.x = ",Child1.x,"Child2.x = ",Child2.x
结果:
Father.x = 11 Mother.x = 22 Child1.x = 11 Child2.x = 11
Father.x = 11 Mother.x = 22 Child1.x = 2 Child2.x = 11
Father.x = 33 Mother.x = 22 Child1.x = 2 Child2.x = 33
Father.x = 33 Mother.x = 44 Child1.x = 2 Child2.x = 33
啊,果然是随爸爸(作为一个大男人我感到很骄傲)。
总结:
1、派生类找不到属性or方法时,会向上寻找之,有该属性or方法的最近的那个。
2、多继承的继承顺序,感觉像是从左到右(好敷衍的总结呢)。