继承的使用原则:
我们要尽量简单的使用继承,或者用组成代替继承,而且做好不要使用多继承。
父类和子类有三个相互影响的方法:
- 子类的动作暗含(imply)了父类的动作
- 子类的动作覆盖(override)了相应的父类动作
- 子类的动作改变(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()
CHILD, BEFORE PARENT altered() #son.altered得出的结果 子类的altered函数变了,
PARENT altered()
CHILD, AFTER PARENT altered()
###### 暂停