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文件读写操作与linux shell变量命令交互执行的方法
Jan 14 Python
Python的ORM框架中SQLAlchemy库的查询操作的教程
Apr 25 Python
详细介绍Python中的偏函数
Apr 27 Python
详解设计模式中的工厂方法模式在Python程序中的运用
Mar 02 Python
对python-3-print重定向输出的几种方法总结
May 11 Python
Django基础知识与基本应用入门教程
Jul 20 Python
Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str
Aug 07 Python
扩展Django admin的list_filter()可使用范围方法
Aug 21 Python
详细整理python 字符串(str)与列表(list)以及数组(array)之间的转换方法
Aug 30 Python
浅谈python中统计计数的几种方法和Counter详解
Nov 07 Python
python小技巧——将变量保存在本地及读取
Nov 13 Python
详解Python中*args和**kwargs的使用
Apr 07 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
判断是否为指定长度内字符串的php函数
2010/02/16 PHP
批量修改RAR文件注释的php代码
2010/11/20 PHP
php删除页面记录 同时刷新页面 删除条件用GET方式获得
2012/01/10 PHP
基于python发送邮件的乱码问题的解决办法
2013/04/25 PHP
PHP安全下载文件的方法
2016/04/07 PHP
用js实现多域名不同文件的调用方法
2007/01/12 Javascript
Locate a File Using a File Open Dialog Box
2007/06/18 Javascript
基于jquery的时间段实现代码
2012/08/02 Javascript
javascript数组的使用
2013/03/28 Javascript
原生javascript兼容性测试实例
2013/07/01 Javascript
addEventListener 的用法示例介绍
2014/05/07 Javascript
jQuery操作表单常用控件方法小结
2015/03/23 Javascript
JavaScript返回0-1之间随机数的方法
2015/04/06 Javascript
JQuery插件Quicksand实现超炫的动画洗牌效果
2015/05/03 Javascript
Javascript字符串拼接小技巧(推荐)
2016/06/02 Javascript
功能强大的Bootstrap效果展示(二)
2016/08/03 Javascript
使用bootstrap-paginator.js 分页来进行ajax 异步分页请求示例
2017/03/09 Javascript
详解使用 Node.js 开发简单的脚手架工具
2018/06/08 Javascript
vue vue-Router默认hash模式修改为history需要做的修改详解
2018/09/13 Javascript
使用 node.js 模仿 Apache 小部分功能
2019/07/07 Javascript
[02:10]三分钟回顾完美世界城市挑战赛
2019/01/24 DOTA
python 字典(dict)遍历的四种方法性能测试报告
2014/06/25 Python
Python闭包之返回函数的函数用法示例
2018/01/27 Python
python3下使用cv2.imwrite存储带有中文路径图片的方法
2018/05/10 Python
详解python中groupby函数通俗易懂
2020/05/14 Python
eVitamins日本:在线购买折扣维生素、补品和草药
2019/04/04 全球购物
浙大网新C/C++面试解惑
2015/05/27 面试题
九州传奇上机题
2014/07/10 面试题
人力资源行政经理自我评价
2013/10/23 职场文书
英文版销售经理个人求职信
2013/11/20 职场文书
另类冲刺标语
2014/06/24 职场文书
2014国庆节幼儿园亲子活动方案
2014/09/16 职场文书
2014年移动公司工作总结
2014/12/08 职场文书
2015年信访工作总结
2015/04/07 职场文书
超级礼物观后感
2015/06/15 职场文书
idea编译器vue缩进报错问题场景分析
2021/07/04 Vue.js