Python 面向对象(4)
2016-07-29 15:22
453 查看
class Vehicle: def __init__(self, speed): self.speed = speed def drive(self, distance): print 'need %f hour(s)' % (distance / self.speed) class Bike(Vehicle): pass class Car(Vehicle): def __init__(self, speed, fuel): Vehicle.__init__(self, speed) self.fuel = fuel def drive(self, distance): Vehicle.drive(self, distance) print 'need %f fuels' % (distance * self.fuel) b = Bike(15.0) c = Car(80.0, 0.012) b.drive(100.0) c.drive(100.0)解释:
__init__函数会在类被创建的时候自动调用,用来初始化类。它的参数,要在创建类的时候提供。于是我们通过提供一个数值来初始化speed的值。
class定义后面的括号里表示这个类继承于哪个类。Bike(Vehicle)就是说Bike是继承自Vehicle中的子类。Vehicle中的属性和方法,Bike都会有。因为Bike不需要有额外的功能,所以用pass在类中保留空块,什么都不用写。
Car类中,我们又重新定义了__init__和drive函数,这样会覆盖掉它继承自Vehicle的同名函数。但我们依然可以通过“Vehicle.函数名”来调用它的超类方法。以此来获得它作为Vehicle所具有的功能。注意,因为是通过类名调用方法,而不是像之前一样通过对象来调用,所以这里必须提供self的参数值。在调用超类的方法之后,我们又给Car增加了一个fuel属性,并且在drive中多输出一行信息。
结果:
need 6.666667 hour(s)
need 1.250000 hour(s)
need 1.200000 fuels
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法