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中os.path用法分析
Jan 15 Python
利用一个简单的例子窥探CPython内核的运行机制
Mar 30 Python
pygame学习笔记(3):运动速率、时间、事件、文字
Apr 15 Python
Python中利用原始套接字进行网络编程的示例
May 04 Python
Python中的rfind()方法使用详解
May 19 Python
Django开发中复选框用法示例
Mar 20 Python
python实现人民币大写转换
Jun 20 Python
python组合无重复三位数的实例
Nov 13 Python
python多进程读图提取特征存npy
May 21 Python
centos7中安装python3.6.4的教程
Dec 11 Python
python中对二维列表中一维列表的调用方法
Jun 07 Python
详解Python的爬虫框架 Scrapy
Aug 03 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
web方式ftp
2006/10/09 PHP
PHP的分页功能
2007/03/21 PHP
在PHP中检查PHP文件是否有语法错误的方法
2009/12/23 PHP
php ftp文件上传函数(基础版)
2010/06/03 PHP
深入php var_dump()函数的详解
2013/06/05 PHP
PHP的curl实现get,post和cookie(实例介绍)
2013/06/17 PHP
php_screw 1.5:php加密: 安装与使用详解
2013/06/20 PHP
php5.5新数组函数array_column使用
2013/07/08 PHP
PHP基于array_unique实现二维数组去重
2020/07/14 PHP
Jquery EasyUI的添加,修改,删除,查询等基本操作介绍
2013/10/11 Javascript
jQuery事件绑定on()、bind()与delegate() 方法详解
2015/06/03 Javascript
使用javascript将时间转换成今天,昨天,前天等格式
2015/06/25 Javascript
jQuery实现的自定义弹出层效果实例详解
2016/09/04 Javascript
jQuery、layer实现弹出层的打开、关闭功能
2017/06/28 jQuery
Angular4表单验证代码详解
2017/09/03 Javascript
Nodejs+angularjs结合multiparty实现多图片上传的示例代码
2017/09/29 NodeJs
vue2单元测试环境搭建
2018/05/24 Javascript
vue中实现左右联动的效果
2018/06/22 Javascript
解决echarts数据二次渲染不成功的问题
2020/07/20 Javascript
selenium 反爬虫之跳过淘宝滑块验证功能的实现代码
2020/08/27 Javascript
移动端JS实现拖拽两种方法解析
2020/10/12 Javascript
Django中对数据查询结果进行排序的方法
2015/07/17 Python
利用python-pypcap抓取带VLAN标签的数据包方法
2019/07/23 Python
使用Python爬虫爬取小红书完完整整的全过程
2021/01/19 Python
HTML5中如何显示视频呢 HTML5视频播放demo
2013/06/08 HTML / CSS
Marmot土拨鼠官网:美国专业户外运动品牌
2018/01/11 全球购物
英国领先的大码时装品牌之一:Elvi
2018/08/26 全球购物
日本订房网站,预订日本星级酒店/温泉旅馆:Relux(支持中文)
2020/01/03 全球购物
人力资源部培训专员岗位职责
2014/01/02 职场文书
大专生毕业的自我评价
2014/02/06 职场文书
《临死前的严监生》教学反思
2014/02/13 职场文书
八项规定个人对照检查材料思想汇报
2014/09/25 职场文书
解除租房协议书
2014/12/03 职场文书
华山导游词
2015/02/03 职场文书
明确岗位职责
2015/02/14 职场文书
员工升职自荐信
2015/03/27 职场文书