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 linecache.getline()读取文件中特定一行的脚本
Sep 06 Python
Python输出9*9乘法表的方法
May 25 Python
python下MySQLdb用法实例分析
Jun 08 Python
批处理与python代码混合编程的方法
May 19 Python
python一键升级所有pip package的方法
Jan 16 Python
关于Tensorflow中的tf.train.batch函数的使用
Apr 24 Python
python的xpath获取div标签内html内容,实现innerhtml功能的方法
Jan 02 Python
python 实现生成均匀分布的点
Dec 05 Python
python GUI库图形界面开发之PyQt5布局控件QHBoxLayout详细使用方法与实例
Mar 06 Python
Python响应对象text属性乱码解决方案
Mar 31 Python
Python urllib2运行过程原理解析
Jun 04 Python
Python实现单例模式的5种方法
Jun 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
一个oracle+PHP的查询的例子
2006/10/09 PHP
php录入页面中动态从数据库中提取数据的实现
2006/10/09 PHP
使用PHP curl模拟浏览器抓取网站信息
2013/10/28 PHP
PHP使用GIFEncoder类生成的GIF动态图片验证码
2014/07/01 PHP
PHP实现自动识别Restful API的返回内容类型
2015/02/07 PHP
PHP在线调试执行的实现方法(附demo源码)
2016/04/28 PHP
PHP7.1方括号数组符号多值复制及指定键值赋值用法分析
2016/09/26 PHP
JQuery 入门实例1
2009/06/25 Javascript
Jsonp 跨域的原理以及Jquery的解决方案
2010/05/18 Javascript
关于jquery append() html时的小问题的解决方法
2010/12/16 Javascript
火狐下input焦点无法重复获取问题的解决方法
2014/06/16 Javascript
基于jQuery实现收缩展开功能
2016/03/18 Javascript
JavaScript调试的多个必备小Tips
2017/01/15 Javascript
node.js+captchapng+jsonwebtoken实现登录验证示例
2017/08/17 Javascript
vue使用showdown并实现代码区域高亮的示例代码
2019/10/17 Javascript
js实现滑动进度条效果
2020/08/21 Javascript
如何在Express4.x中愉快地使用async的方法
2020/11/18 Javascript
[02:05]2014DOTA2西雅图邀请赛 老队长全明星大猜想谁不服就按进显示器
2014/07/08 DOTA
python解析xml文件操作实例
2014/10/05 Python
python根据文件大小打log日志
2014/10/09 Python
Python socket实现简单聊天室
2018/04/01 Python
使用pandas中的DataFrame数据绘制柱状图的方法
2018/04/10 Python
Python多重继承的方法解析执行顺序实例分析
2018/05/26 Python
python学生管理系统学习笔记
2019/03/19 Python
python GUI库图形界面开发之PyQt5窗口类QMainWindow详细使用方法
2020/02/26 Python
PyTorch中的C++扩展实现
2020/04/02 Python
Python基于Tkinter编写crc校验工具
2020/05/06 Python
Python使用Chrome插件实现爬虫过程图解
2020/06/09 Python
keras的三种模型实现与区别说明
2020/07/03 Python
Radley英国官网:英国莱德利小狗包
2019/03/21 全球购物
耐克奥地利官网:Nike奥地利
2019/08/16 全球购物
大学生实习自我鉴定
2013/12/11 职场文书
统计学教授推荐信
2014/09/18 职场文书
工作批评与自我批评范文
2014/10/16 职场文书
南京导游词
2015/02/03 职场文书
四年级作文之植物
2019/09/20 职场文书