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 Socket实现简单TCP Server/client功能示例
Aug 05 Python
python取代netcat过程分析
Feb 10 Python
python matplotlib绘图,修改坐标轴刻度为文字的实例
May 25 Python
对python添加模块路径的三种方法总结
Oct 16 Python
Django restframework 源码分析之认证详解
Feb 22 Python
Python判断有效的数独算法示例
Feb 23 Python
Puppeteer使用示例详解
Jun 20 Python
用sqlalchemy构建Django连接池的实例
Aug 29 Python
安装完Python包然后找不到模块的解决步骤
Feb 13 Python
numpy的Fancy Indexing和array比较详解
Jun 11 Python
解决python的空格和tab混淆而报错的问题
Feb 26 Python
总结Python常用的魔法方法
May 25 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
删除无限分类并同时删除它下面的所有子分类的方法
2010/08/08 PHP
php创建sprite
2014/02/11 PHP
php操作csv文件代码实例汇总
2014/09/22 PHP
php控制文件下载速度的方法
2015/03/24 PHP
php获取远程文件大小
2015/10/20 PHP
Yii框架的路由配置方法分析
2019/09/09 PHP
thinkphp5框架路由原理与用法详解
2020/02/11 PHP
js类中的公有变量和私有变量
2008/07/24 Javascript
使用js对select动态添加和删除OPTION示例代码
2013/08/12 Javascript
wap图片滚动特效无css3元素纯js脚本编写
2014/08/22 Javascript
windows下安装nodejs及框架express
2015/08/07 NodeJs
Bootstrap每天必学之简单入门
2015/11/19 Javascript
深入理解setTimeout函数和setInterval函数
2016/05/20 Javascript
jQuery的图片轮播插件PgwSlideshow使用详解
2016/08/11 Javascript
3种不同的ContextMenu右键菜单实现代码
2016/11/03 Javascript
JavaScript 隐性类型转换步骤浅析
2018/03/15 Javascript
深入理解 Koa 框架中间件原理
2018/10/18 Javascript
详解vue 项目白屏解决方案
2018/10/31 Javascript
[02:59]2014DOTA2西雅图国际邀请赛 圆满落幕中国夺冠
2014/07/23 DOTA
[01:24]DOTA2上海特锦赛OG战队抵达 专车接机入驻总统套房
2016/02/23 DOTA
python访问纯真IP数据库的代码
2011/05/19 Python
Python中的浮点数原理与运算分析
2017/10/12 Python
Python定义二叉树及4种遍历方法实例详解
2018/07/05 Python
Django基础知识 URL路由系统详解
2019/07/18 Python
Python 调用有道翻译接口实现翻译
2020/03/02 Python
工程师必须了解的LRU缓存淘汰算法以及python实现过程
2020/10/15 Python
设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
2014/12/30 面试题
女子职高个人自荐书
2014/02/01 职场文书
社区安全检查制度
2014/02/03 职场文书
房产公证书范本
2014/04/10 职场文书
贷款承诺书范文
2014/05/19 职场文书
材料物理专业求职信
2014/09/01 职场文书
大学生简短的自我评价
2014/09/12 职场文书
2015年团支部工作总结
2015/04/03 职场文书
施工安全保证书
2015/05/09 职场文书
贫困证明怎么写
2015/06/16 职场文书