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使用wxpython开发简单记事本的方法
May 20 Python
python利用正则表达式搜索单词示例代码
Sep 24 Python
python执行使用shell命令方法分享
Nov 08 Python
简单实现Python爬取网络图片
Apr 01 Python
PyCharm代码整体缩进,反向缩进的方法
Jun 25 Python
python中sys.argv函数精简概括
Jul 08 Python
Python3实现统计单词表中每个字母出现频率的方法示例
Jan 28 Python
python启动应用程序和终止应用程序的方法
Jun 28 Python
详解python解压压缩包的五种方法
Jul 05 Python
python验证码图片处理(二值化)
Nov 01 Python
Django框架下静态模板的继承操作示例
Nov 08 Python
用60行代码实现Python自动抢微信红包
Feb 04 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微信刮刮卡 附微信接口
2016/07/22 PHP
使弱类型的语言JavaScript变强势
2009/06/22 Javascript
Tinymce+jQuery.Validation使用产生的BUG
2010/03/29 Javascript
js实现弹窗插件功能实例代码分享
2013/12/12 Javascript
addEventListener 的用法示例介绍
2014/05/07 Javascript
浅谈javascript中的instanceof和typeof
2015/02/27 Javascript
jQuery模拟新浪微博首页滚动效果的方法
2015/03/11 Javascript
Nodejs如何搭建Web服务器
2016/03/28 NodeJs
AngularJs 弹出模态框(model)
2016/04/07 Javascript
JS使用JSON作为参数实例分析
2016/06/23 Javascript
关于JSON.parse(),JSON.stringify(),jQuery.parseJSON()的用法
2016/06/30 Javascript
微信小程序自定义toast实现方法详解【附demo源码下载】
2017/11/28 Javascript
微信小程序实现图片选择并预览功能
2019/07/25 Javascript
vue2.x 通过后端接口代理,获取qq音乐api的数据示例
2019/10/30 Javascript
Javascript实现秒表计时游戏
2020/05/27 Javascript
微信小程序自定义顶部组件customHeader的示例代码
2020/06/03 Javascript
python获取指定目录下所有文件名列表的方法
2015/05/20 Python
Python中正则表达式详解
2017/05/17 Python
Python实现微信消息防撤回功能的实例代码
2019/04/29 Python
python基于pdfminer库提取pdf文字代码实例
2019/08/15 Python
深入学习python多线程与GIL
2019/08/26 Python
Python程序暂停的正常处理方法
2019/11/07 Python
python os模块在系统管理中的应用
2020/06/22 Python
如何用Python进行时间序列分解和预测
2021/03/01 Python
捷克时尚网上商店:OTTO
2018/03/15 全球购物
Nike澳大利亚官网:Nike.com (AU)
2019/06/03 全球购物
台湾屈臣氏网路商店:Watsons台湾
2020/12/29 全球购物
关于Java finally的面试题
2016/04/27 面试题
2014年小学元旦活动方案
2014/02/12 职场文书
银行求职信怎么写
2014/05/26 职场文书
个人优缺点总结
2015/02/28 职场文书
公司欠款证明
2015/06/24 职场文书
初中运动会前导词
2015/07/20 职场文书
详解Vue项目的打包方式(生成dist文件)
2022/01/18 Vue.js
《杜鹃的婚约》OP主题曲「凸凹」无字幕影像公开
2022/04/08 日漫
使用Mysql计算地址的经纬度距离和实时位置信息
2022/04/29 MySQL