python 当派生类找不到属性、方法时会怎么办

面试题之一。

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、多继承的继承顺序,感觉像是从左到右(好敷衍的总结呢)。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值