python 继承
2017-09-22 17:18
239 查看
继承: 创建一个子类和创建一个类是很相似的,你只需要提供一个或多尔个基类(不是对象)就行了。 实例化: 其他语言一般都使用new语句来创建实例,不过Python里你只要像调用函数一样调用类的名字就可以了。 Python 用的是"初始化程序"而不是构造函数。 所以名字用的也是__init__,在实例化一个对象时,你需要传入__init__所需的参数。 在OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类 而被继承的类称为基类,父类或者超类 class Animal(object): def __init__(self): print self def run(self,a,b): return a + b ##实例化对象 a=Animal() ##调用实例方法 print a.run(3,4) C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a9.py <__main__.Animal object at 0x02177E30> 7 [oracle@node01 web]$ vim Animal.py [oracle@node01 web]$ pwd /oracle/python/mycompany/web [oracle@node01 web]$ ls -ltr Animal.py -rw-r--r-- 1 oracle dba 109 Sep 4 16:55 Animal.py 导入模块: [oracle@node01 python]$ pwd /oracle/python [oracle@node01 python]$ cat 91.py from mycompany.web.Animal import * a=Animal() print a.run(3,4) [oracle@node01 python]$ python 91.py <mycompany.web.Animal.Animal object at 0x7fd6fad09690> 7 继承: [oracle@node01 web]$ cat Animal.py class Animal(object): def __init__(self): print self def run(self,a,b): return a + b def update(self,a,b): return a-b [oracle@node01 python]$ cat 92.py from mycompany.web.Animal import * class Dog(Animal): def __init__(self): print self def run(self,a,b): return a+b+9 a=Dog() print a.run(3,4) [oracle@node01 python]$ python 92.py <__main__.Dog object at 0x7fec3354d7d0> 16 当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。 这样,我们就获得了继承的另一个好处:多态。 [oracle@node01 python]$ cat 92.py from mycompany.web.Animal import * class Dog(Animal): def __init__(self): print self def run(self,a,b): return a+b+9 a=Dog() print a.run(3,4) print a.update(66,12) [oracle@node01 python]$ python 92.py <__main__.Dog object at 0x7fd2836bf7d0> 16 54
相关文章推荐
- Python:类的继承关系
- Python中的多态与继承
- 转 python语法学习面向对象之继承
- python基础----多态与多态性、super函数用法、继承原理
- 深入super,看Python如何解决钻石继承难题 【转】
- 论python3下“多态”与“继承”中坑
- python---面向对象,class定义、构造函数、析构函数、基本继承
- 流畅的python第十二章继承的优缺点学习记录
- Python - 继承object类
- Python的高级特性12:类的继承
- python 继承和多态
- Python练习代码 -- 类, 继承
- Python 多继承
- 【python】继承 定制 使用元类
- Python面向对象,类,继承,多态及鸭子类型,获取类的类型,方法和属性(类似java的反射)
- [Python]通过继承覆盖方法
- python类继承用法实例分析
- python新式类多重继承 广度优先搜索 C3算法
- Python的继承以及调用父类成员:super用法
- Python入门的36个例子 之 32 -> OOP – Inheritance 继承