赵乐ACM

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. python中的继承

class Parent(object):

    def override(self):
        print "PARENT override()"

    def implicit(self):
        print "PARENT implicit()"

    def altered(self):
        print "PARENT altered()"

class Child(Parent):

    def override(self):
        print "CHILD override()"

    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered() #注意super的用法!!!!
        print "CHILD, AFTER PARENT altered()"

dad = Parent()
son = Child()

dad.implicit()
son.implicit()

dad.override()
son.override()

dad.altered()
son.altered()

python可以多重继承,即一个class可以有多个父类。

class Son(Dad, Mum):
    pass

这时,当调用super(Son, self).***()的时候,会看Dad里有没有这个方法,如果有,就不调用Mum里的了,如果没有,才查看Mum里有没有,看下面的代码:

class Parent(object):

    def override(self):
        print "PARENT override"

    def implicit(self):
        print "PARENT implicit"

    def altered(self):
        print "PARENT altered"

class Mum(object):
    def altered1(self):
        print "MUM, altered."

class Child(Mum, Parent):

    def override(self):
        print "CHILD override"

    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered1()
        super(Child, self).altered()

        print "CHILD, AFTER PARENT altered()"

dad = Parent()
son = Child()

dad.implicit()
son.implicit()

dad.override()
son.override()

dad.altered()
son.altered()

输出结果:

E:\SkyDrive\python\the hard way to learn python>python ex44_4.py
PARENT implicit
PARENT implicit
PARENT override
CHILD override
PARENT altered
CHILD, BEFORE PARENT altered()
MUM, altered.
PARENT altered
CHILD, AFTER PARENT altered()

 

posted on 2013-03-23 21:50  赵乐ACM  阅读(162)  评论(0编辑  收藏  举报