类的继承

python之面向对象(继承)

面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系。

需要注意的地方:继承语法 class 派生类名(基类名)://... 基类名写作括号里,基本类是在类定义的时候,在元组之中指明的。

在python中继承中的一些特点:

  1. 在继承中基类的构造(init()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。

  2. 在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数.

  3. Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。


class animal(object):
def __init__(self):
print 'animal init' def say(self):
print 'animal say' class dog(animal):
def __init__(self):
#animal.__init__(self)
print 'dog init' def say(self):
animal.say(self)
print 'dog say'

In [23]:

d = dog()
d.say()

out:

dog init
animal say
dog say

如果在继承元组中列了一个以上的类,那么它就被称作"多重继承" 。

当多个类之间有包含关系,不能继承。

比如,下面的例子不行。

class A:
class B(A):
class C(A,B)

下面是,多重继承逐个查找的示例:

class animal(object):
def __init__(self):
print 'animal init' def say(self):
print 'animal say' class dog(animal):
def __init__(self):
#animal.__init__(self)
print 'dog init' def say(self):
animal.say(self)
print 'dog say' class cat(animal):
def __init__(self):
#animal.__init__(self)
print 'cat init' def say(self):
#animal.say(self)
print 'cat say' class wolfhound(cat,dog): #先继承cat,后面测试案例只输出了cat say。
def __init__(self):
print "wolfhound init." def run(self):
print "wolfhound run"

in:

d = dog()
d.say()
w = wolfhound()
w.run()
w.say()

out:

dog init
animal say
dog say
wolfhound init.
wolfhound run
cat say

最新文章

  1. .net 下新版highcharts本地导出图片bug处理
  2. 在 Windows 上安装Rabbit MQ 指南
  3. Horseman - 让你更轻松的使用 PhantomJS
  4. Windows2003系统问题:“无法加载安装程序库wbemupgd.dll,或是找不到函数OcEntry.
  5. Second Day learning English
  6. map学习笔记
  7. CMDB反思3
  8. chrome启用本地文件
  9. The usage of V$PGA_TARGET_ADVICE
  10. 201521123009 《Java程序设计》第6周学习总结
  11. python中with学习
  12. 关于new Date()的日期格式处理
  13. LINUX 常用命令(二)
  14. [Swift]LeetCode989. 数组形式的整数加法 | Add to Array-Form of Integer
  15. cf1088D Ehab and another another xor problem (构造)
  16. 【bzoj 3779】重组病毒
  17. ECharts.js学习(一) 简单入门
  18. 作为非计算机专业的学生,觉得 C 语言远比其他语言易于上手,正常吗?
  19. C++类型检查
  20. Git 基础 —— 常见使用场景

热门文章

  1. java 判断一个字符串中的数字:是否为数字、是否包含数字、截取数字
  2. poj1679次小生成树入门题
  3. LeetCode OJ:Palindrome Partitioning(回文排列)
  4. 【javascript基础】 原生JSON.parse解析异常问题
  5. Week08《Java程序设计》第八次学习总结
  6. restify构建REST服务(转)
  7. Django部署时为什么要用 uWSGI与 Nginx? 以及 WSGI,uwsgi等协议
  8. Spring AOP的使用报错!
  9. 转-redux-saga
  10. 前端构建工具-fis3使用入门