python继承和抽象类的实现方法


Posted in Python onJanuary 14, 2015

本文实例讲述了python继承和抽象类的实现方法。分享给大家供大家参考。

具体实现方法如下:

#!/usr/local/bin/python

# Fig 9.9: fig09_09.py

# Creating a class hierarchy with an abstract base class.

 

class Employee:

   """Abstract base class Employee"""

 

   def __init__(self, first, last):

      """Employee constructor, takes first name and last name.

      NOTE: Cannot create object of class Employee."""

 

      if self.__class__ == Employee:

         raise NotImplementedError, \

            "Cannot create object of class Employee"

 

      self.firstName = first

      self.lastName = last

 

   def __str__(self):

      """String representation of Employee"""

 

      return "%s %s" % (self.firstName, self.lastName)

 

   def _checkPositive(self, value):

      """Utility method to ensure a value is positive"""

 

      if value < 0:

         raise ValueError, \

            "Attribute value (%s) must be positive" % value

      else:

         return value

 

   def earnings(self):

      """Abstract method; derived classes must override"""

 

      raise NotImplementedError, "Cannot call abstract method"

 

class Boss(Employee):

   """Boss class, inherits from Employee"""

 

   def __init__(self, first, last, salary):

      """Boss constructor, takes first and last names and salary"""

 

      Employee.__init__(self, first, last)

      self.weeklySalary = self._checkPositive(float(salary))

 

   def earnings(self):

      """Compute the Boss's pay"""

 

      return self.weeklySalary

 

   def __str__(self):

      """String representation of Boss"""

 

      return "%17s: %s" % ("Boss", Employee.__str__(self))

 

class CommissionWorker(Employee):

   """CommissionWorker class, inherits from Employee"""

 

   def __init__(self, first, last, salary, commission, quantity):

      """CommissionWorker constructor, takes first and last names,

      salary, commission and quantity"""

 

      Employee.__init__(self, first, last)

      self.salary = self._checkPositive(float(salary))

      self.commission = self._checkPositive(float(commission))

      self.quantity = self._checkPositive(quantity)

 

   def earnings(self):

      """Compute the CommissionWorker's pay"""

 

      return self.salary + self.commission * self.quantity

 

   def __str__(self):

      """String representation of CommissionWorker"""

 

      return "%17s: %s" % ("Commission Worker",

         Employee.__str__(self))

 

class PieceWorker(Employee):

   """PieceWorker class, inherits from Employee"""

 

   def __init__(self, first, last, wage, quantity):

      """PieceWorker constructor, takes first and last names, wage

      per piece and quantity"""

 

      Employee.__init__(self, first, last)

      self.wagePerPiece = self._checkPositive(float(wage))

      self.quantity = self._checkPositive(quantity)

 

   def earnings(self):

      """Compute PieceWorker's pay"""

 

      return self.quantity * self.wagePerPiece

 

   def __str__(self):

      """String representation of PieceWorker"""

 

      return "%17s: %s" % ("Piece Worker",

         Employee.__str__(self))

 

class HourlyWorker(Employee):

   """HourlyWorker class, inherits from Employee"""

 

   def __init__(self, first, last, wage, hours):

      """HourlyWorker constructor, takes first and last names,

      wage per hour and hours worked"""

 

      Employee.__init__(self, first, last)

      self.wage = self._checkPositive(float(wage))

      self.hours = self._checkPositive(float(hours))

 

   def earnings(self):

      """Compute HourlyWorker's pay"""

 

      if self.hours <= 40:

         return self.wage * self.hours

      else:

         return 40 * self.wage + (self.hours - 40) * \

           self.wage * 1.5

 

   def __str__(self):

      """String representation of HourlyWorker"""

 

      return "%17s: %s" % ("Hourly Worker",

         Employee.__str__(self))

 

# main program

 

# create list of Employees

employees = [ Boss("John", "Smith", 800.00),

              CommissionWorker("Sue", "Jones", 200.0, 3.0, 150),

              PieceWorker("Bob", "Lewis", 2.5, 200),

              HourlyWorker("Karen", "Price", 13.75, 40) ]

 

# print Employee and compute earnings

for employee in employees:

   print "%s earned $%.2f" % (employee, employee.earnings())

输出结果如下:

Boss: John Smith earned $800.00

Commission Worker: Sue Jones earned $650.00

Piece Worker: Bob Lewis earned $500.00

Hourly Worker: Karen Price earned $550.00

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python基础教程之类class定义使用方法
Feb 20 Python
简单谈谈python中的多进程
Nov 06 Python
Python编程实现粒子群算法(PSO)详解
Nov 13 Python
Python处理文本换行符实例代码
Feb 03 Python
使用python3+xlrd解析Excel的实例
May 04 Python
pycharm 取消默认的右击运行unittest的方法
Nov 29 Python
python实现网页自动签到功能
Jan 21 Python
Django实现web端tailf日志文件功能及实例详解
Jul 28 Python
Python对列表的操作知识点详解
Aug 20 Python
查看jupyter notebook每个单元格运行时间实例
Apr 22 Python
Pytorch 使用opnecv读入图像由HWC转为BCHW格式方式
Jun 02 Python
Python获取android设备cpu和内存占用情况
Nov 15 Python
python列表操作实例
Jan 14 #Python
python操作gmail实例
Jan 14 #Python
Python中的装饰器用法详解
Jan 14 #Python
python登陆asp网站页面的实现代码
Jan 14 #Python
Python的面向对象思想分析
Jan 14 #Python
为python设置socket代理的方法
Jan 14 #Python
Python单例模式实例分析
Jan 14 #Python
You might like
国产动画《伍六七》原声大碟大卖,啊哈娱乐引领音乐赋能IP的新尝试
2020/03/08 国漫
PHP在不同页面间传递Json数据示例代码
2013/06/08 PHP
微信支付开发教程(一)微信支付URL配置
2014/05/28 PHP
针对多用户实现头像上传功能PHP代码 适用于登陆页面制作
2016/08/17 PHP
JQuery AJAX实现目录浏览与编辑的代码
2008/10/21 Javascript
Underscore.js 的模板功能介绍与应用
2012/12/24 Javascript
js实现单一html页面两套css切换代码
2013/04/11 Javascript
jQuery中 noConflict() 方法使用
2013/04/25 Javascript
JavaScript全排列的六种算法 具体实现
2013/06/29 Javascript
jquery设置text的值示例(设置文本框 DIV 表单值)
2014/01/06 Javascript
javascript制作坦克大战全纪录(2)
2014/11/27 Javascript
基于javascript实现漂亮的页面过渡动画效果附源码下载
2015/10/26 Javascript
Extjs4.0 ComboBox如何实现三级联动
2016/05/11 Javascript
BootStrap扔进Django里的方法详解
2016/05/13 Javascript
关于jquery中动态增加select,事件无效的快速解决方法
2016/08/29 Javascript
JavaScript条件判断_动力节点Java学院整理
2017/06/26 Javascript
深入理解Vue transition源码分析
2017/07/30 Javascript
JS实现可视化文件上传
2018/09/08 Javascript
微信小程序实现tab左右切换效果
2020/11/15 Javascript
PHPStorm中如何对nodejs项目进行单元测试详解
2019/02/28 NodeJs
微信小程序 wepy框架与iview-weapp的用法详解
2019/04/10 Javascript
jquery插件懒加载的示例
2020/10/24 jQuery
[00:11]战神迅矛
2019/03/06 DOTA
对python多线程与global变量详解
2018/11/09 Python
总结Pyinstaller的坑及终极解决方法(小结)
2020/09/21 Python
澳大利亚最大的女装零售商:Millers
2017/09/10 全球购物
西班牙香水和化妆品连锁店:Druni
2019/05/05 全球购物
测控技术与仪器个人求职信范文
2013/12/30 职场文书
我的动漫时代的创业计划书范文
2014/01/27 职场文书
销售经理工作职责
2014/02/03 职场文书
餐厅楼面部长岗位职责范文
2014/02/16 职场文书
委托书样本
2014/04/02 职场文书
社区综治工作汇报
2014/10/27 职场文书
优秀英文求职信范文
2015/03/19 职场文书
2019西餐厅创业计划书范文!
2019/07/12 职场文书
python模块与C和C++动态库相互调用实现过程示例
2021/11/02 Python