多态
来源:互联网 发布:mac sdk 环境变量配置 编辑:程序博客网 时间:2024/06/05 13:54
要理解什么是多态,我们首先要对数据类型再作一点说明,当我们定义一个class的时候,我们实际上就定义了一种数据类型,我们定义的数据类型和Python自带的数据类型,比如str,list,dict没什么两样:class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print '%s: %s' % (self.name, self.score -2)from mycompany.web.Student import *c = Student('a',88)print c.nameprint isinstance(c, Student)print c.print_score()C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.pyaTruea: 86Nonea = list() # a是list类型b = Animal() # b是Animal类型c = Dog() # c是Dog类型判断一个变量是否是某个类型可以用isinstance()判断:>>> isinstance(a, list)True>>> isinstance(b, Animal)True>>> isinstance(c, Dog)Trufrom mycompany.web.Dog import *c = Dog()c.run()print isinstance(c, Dog)print isinstance(c, Animal)C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.pyyyAnimal is running...TrueTruefrom mycompany.web.Dog import *b = Animal()print b.run()C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.pyyyAnimal isxx running...Nonefrom mycompany.web.Dog import *def run_twice(animal): animal.run()print '----------------'run_twice(Animal())run_twice(Dog())C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py----------------Animal isxx running...Dog isxx running...Process finished with exit code 0看上去没啥意思,但是仔细想想,现在,如果我们再定义一个Tortoise类型,也从Animal派生:class Tortoise(Animal): def run(self): print 'Tortoise is running slowly...'from mycompany.web.Tortoise import *def run_twice(animal): animal.run()print '----------------'run_twice(Animal())run_twice(Tortoise())C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py----------------Animal isxx running...Tortoise is running slowly...Process finished with exit code 0你会发现,新增一个Animal的子类,不必对run_twice()做任何修改,实际上,任何依赖Animal 作为的函数的函数或者方法都可以不加修改地正常运行,原因在于多态from mycompany.web.Tortoise import *def run_twice(animal): animal.run()print '----------------'run_twice(Animal())run_twice(Tortoise())C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.pyxxxx----------------Animal isxx running...Animal isxx running...
阅读全文
0 0
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 老毛桃地址
- Ajax实现原理详解
- ((NULL) null).printNULL();((NULL) null).printnull();
- MySQL数据库SYS CPU高的可能性分析
- EventBus讲解
- 多态
- Hibernate的关联关系注解映射(一对一、一对多、多对一、多对多、自连接) 标签: hibernateentity 2016-10-11 16:28 1635人阅读 评论(0) 收藏 举报 分类
- 多路查找树——2-3树——B树
- RocketMQ——Consumer篇:启动过程
- springcloud(六):配置中心git示例
- Cloudsim 3.0.3中任务到VM的映射
- hdu3041 单调队列优化dp
- [Linux] df -h 回显不全
- js全局函数以及重载