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 相关文章推荐
Fiddler如何抓取手机APP数据包
Jan 22 Python
python实现百度语音识别api
Apr 10 Python
Python采集代理ip并判断是否可用和定时更新的方法
May 07 Python
python遍历文件夹,指定遍历深度与忽略目录的方法
Jul 11 Python
关于django 1.10 CSRF验证失败的解决方法
Aug 31 Python
python利用openpyxl拆分多个工作表的工作簿的方法
Sep 27 Python
Python模块汇总(常用第三方库)
Oct 07 Python
python使用PIL剪切和拼接图片
Mar 23 Python
django实现更改数据库某个字段以及字段段内数据
Mar 31 Python
基于Python测试程序是否有错误
May 16 Python
Jupyter notebook 不自动弹出网页的解决方案
May 21 Python
Python基础教程,Python入门教程(超详细)
Jun 24 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 var_dump()函数的详解
2013/06/05 PHP
PHP无限分类(树形类)
2013/09/28 PHP
php 魔术方法详解
2014/11/11 PHP
php实现XSS安全过滤的方法
2015/07/29 PHP
php bootstrap实现简单登录
2016/03/08 PHP
PHP实现在数据库百万条数据中随机获取20条记录的方法
2017/04/19 PHP
利用PHPStorm如何开发Laravel应用详解
2017/08/30 PHP
php+lottery.js实现九宫格抽奖功能
2019/07/21 PHP
jQuery使用一个按钮控制图片的伸缩实现思路
2013/04/19 Javascript
Javascript浅谈之this
2013/12/17 Javascript
javaScript使用EL表达式的几种方式
2014/05/27 Javascript
JavaScript中的getDay()方法使用详解
2015/06/09 Javascript
Nginx上传文件全部缓存解决方案
2015/08/17 Javascript
详解JavaScript实现设计模式中的适配器模式的方法
2016/05/18 Javascript
VUE 更好的 ajax 上传处理 axios.js实现代码
2017/05/10 Javascript
Angular2使用Angular-CLI快速搭建工程(二)
2017/05/21 Javascript
基于LayUI分页和LayUI laypage分页的使用示例
2017/08/02 Javascript
bootstrap轮播模板使用方法详解
2017/11/17 Javascript
JS脚本实现网页自动秒杀点击
2018/01/11 Javascript
nodejs中函数的调用实例详解
2018/10/31 NodeJs
微信小程序实现下拉框功能
2019/07/16 Javascript
python实现人脸识别代码
2017/11/08 Python
神经网络理论基础及Python实现详解
2017/12/15 Python
python去重,一个由dict组成的list的去重示例
2019/01/21 Python
python实时检测键盘输入函数的示例
2019/07/17 Python
python -v 报错问题的解决方法
2020/09/15 Python
Django如何实现防止XSS攻击
2020/10/13 Python
recorder.js 基于Html5录音功能的实现
2020/05/26 HTML / CSS
程序集与命名空间有什么不同
2014/07/25 面试题
工程招投标邀请书
2014/01/26 职场文书
工作评语大全
2014/04/26 职场文书
群众路线个人剖析材料
2014/10/07 职场文书
2015年教育实习工作总结
2015/04/24 职场文书
2015年扫黄打非工作总结
2015/05/13 职场文书
2016年综治和平安建设宣传月活动总结
2016/04/01 职场文书
golang操作redis的客户端包有多个比如redigo、go-redis
2022/04/14 Golang