习题 44 继承与合成

2017-10-14  本文已影响0人  南北东西总相随

习题 44 继承与合成

隐式继承

class Parent(object):
    def implicit(self):
        print "PARENT implicit()"

class Child(Parent):
    pass

dad = Parent()
son = Child()

dad.implicit()
son.implicit()

结果:

PARENT implicit()
PARENT implicit()

显式覆盖

class Parent(object):
    def override(self):
        print "PARENT override()"

class Child(Parent):
    def override(self):
        print "CHILD override()"

dad = Parent()
son = Child()

dad.override()
son.override()

结果:

PARENT override()
CHILD override()

在运行前或运行后替换

class Parent(object):
    def altered(self):
        print "PARENT altered()"

class Child(Parent):
    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered() # 调用父类方法
        print "CHILD, AFTER PARENT altered()"

dad = Parent()
son = Child()

dad.altered()
son.altered()

结果:

PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()

三种方式组合使用

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()
        print "CHILD, AFTER PARENT altered()"

dad = Parent()
son = Child()

print "*** IMPLICIT ***"
dad.implicit()
son.implicit()

print "*** OVERRIDE ***"
dad.override()
son.override()

print "*** ALTERED ***"
dad.altered()
son.altered()

结果:

*** IMPLICIT ***
PARENT implicit()
PARENT implicit()
*** OVERRIDE ***
PARENT override()
CHILD override()
*** ALTERED ***
PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()

super()__init__搭配使用

class Child(Parent):
    def __init__(self, stuff):
        self.stuff = stuff
        super(Child, self).__init__() # 调用父类的初始化方法

合成

class Other(object):
    def override(self):
        print "OTHER override()"

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

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

class Child(object):
    def __init__(self):
        self.other = Other()

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

    def implicit(self):
        self.other.implicit()

    def altered(self):
        print "CHILD, BEFORE OTHER altered()"
        self.other.altered()
        print "CHILD, AFTER OTHER altered()"

son = Child()

son.implicit()
son.override()
son.altered()

结果:

OTHER implicit()
CHILD override()
CHILD, BEFORE OTHER altered()
OTHER altered()
CHILD, AFTER OTHER altered()
上一篇下一篇

猜你喜欢

热点阅读