ex44 继承还是组成

继承的使用原则:

我们要尽量简单的使用继承,或者用组成代替继承,而且做好不要使用多继承。


父类和子类有三个相互影响的方法:

  1. 子类的动作暗含(imply)了父类的动作
  2. 子类的动作覆盖(override)了相应的父类动作
  3. 子类的动作改变(alter)了相应的父类动作
暗含继承 Implicit Inheritance
先在父类定义一个implicit函数,子类什么也不做。
First I will show you the implicit actions that happen when you define a function in the parent, but not in the child.
首先展示暗含行为,在父类定义函数,子类中不定义。

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()
子类会自动取得父类的所有特征,不需要重复编写代码。

覆盖暗含 Override Explicitly(覆盖 明确)
继承的问题是有时候你希望子类有不同的函数能干不一样的事情,解决办法就是在子类中覆盖父类的函数,在子类中定义一个同名的函数(在子类中创建同名函数,并不会影响父类中的函数。)

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()

改变之前或者之后
The third way to use inheritance is a special case of overriding where you want to alter the behavior before or after the Parent class's version runs. You first override the function just like in the last example, but then you use a Python built-in function named super to get the Parent version to call. Here's the example of doing that so you can make sense of this description:
改变(alter)是一种特殊的覆盖(override)我们需要像上一个例子一样覆盖父类的函数,然后通过super调用父类的函数。

class Parent(object):

    def altered(self):
        print "PARENT altered()"  #1原来父类的内容

class Child(Parent):

    def altered(self):
        print "CHILD, BEFORE PARENT altered()"     #子类修改父类的altered函数
        super(Child, self).altered()               #super函数找Child的父类,调用父类,所以后面显示PARENT altered?????
        print "CHILD, AFTER PARENT altered()"      #

dad = Parent()
son = Child()

dad.altered()
son.altered()
PARENT altered()                                #来自#1 原来的父类 dad.altered()
CHILD, BEFORE PARENT altered()   #son.altered得出的结果 子类的altered函数变了,
PARENT altered()    
CHILD, AFTER PARENT altered()


###### 暂停




















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值