文章标题
来源:互联网 发布:吊带承重数据 编辑:程序博客网 时间:2024/05/20 03:38
python中继承的三种方式
这里面包含两种关系:is-a,has-a。
完全继承
这是is-a的关系,就是子类直接继承于父类。
class Parent(object): def implicit(self): print "PARENT implicit()"class Child(Parent): passdad = Parent()son = Child()dad.implicit()son.implicit()
运行的结果:
PARENT implicit() PARENT implicit()
son没有implicit方法,由于继承的是parent,parent有,son就可以直接使用。
继承中稍有不同
比如son要有在继承了parent的基础上,有点自己的内容,那怎么办呢?python为我们提供了super()方法
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()
这里son中的altered()的super(Child, self).altered()
这个语句就直接调用了parent的altered()方法,但是在son的altered()又有自己的内容:前后两个print。
所以son的altered()方法就打印了三段内容。
使用super()和init相结合的方法实现间接继承
这种方法属于has-a关系,我们首先来看这样一段代码
class Child(Parent): def __init__(self, stuff): self.stuff = stuff super(Child, self).__init__()
在这段代码中,我们定义了一个child类,然后在初始化的过程中,这句代码super(Child, self).__init__()
实现了对父类的初始化。
这与之前的child.altered()方法十分类似,唯一不同的是:我们在父类没有使用Parent.__init__
初始化之前,就在子类的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 implicit(self): self.other.implicit() def override(self): print "CHILD override()" 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()
由此可以见,在定义了other这个类之后,我们只要在child的初始化中,加上这样一句: self.other = Other()
就可以直接调用other类中的方法了。由于other没有自定义的init(),所以在son的init()中也不需要对other类进行初始化了。直接调用即可^_~
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 2016.4.12 nature deep learning review[2]
- 2016.4.15 nature deep learning review[3]
- 2016.4.15 近期要读的论文
- 2016.4.15 Yann Lecun 的 LeNet-5
- 2016.4.15 Receptive fields, binocular interaction and functional architecture in the cat\'s visual cortex
- 文章标题
- 2016.4.16 Gradient-based learning applied to document recognition[待更]
- 2016.4.17 并行计算课程
- 《java语言程序设计》泽勒一致性问题
- Java之------单机版书店管理系统(设计思想和设计模式系列一)概述
- java学习笔记(十五)
- 例说定时器System.Threading.Timer
- select_echo_server
- 数据结构——排序算法