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抓取某汽车网数据解析html存入excel示例
Dec 04 Python
使用Python生成url短链接的方法
May 04 Python
python实现批量按比例缩放图片效果
Mar 30 Python
python实现在pandas.DataFrame添加一行
Apr 04 Python
Python之dict(或对象)与json之间的互相转化实例
Jun 05 Python
python+opencv实现阈值分割
Dec 26 Python
Python读取csv文件分隔符设置方法
Jan 14 Python
python基础教程之while循环
Aug 14 Python
Python帮你识破双11的套路
Nov 11 Python
Django中modelform组件实例用法总结
Feb 10 Python
利用python控制Autocad:pyautocad方式
Jun 01 Python
Python JSON常用编解码方法代码实例
Sep 05 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
基于magic_quotes_gpc与magic_quotes_runtime的区别与使用介绍
2013/04/22 PHP
Thinkphp连表查询及数据导出方法示例
2016/10/15 PHP
php根据用户名和手机号查询是否存在手机号码
2017/02/16 PHP
很好用的js日历算法详细代码
2013/03/07 Javascript
javascript中加号(+)操作符的一些神奇作用
2014/06/06 Javascript
javascript学习笔记(四)function函数部分
2014/09/30 Javascript
用js读写cookie的简单方法(推荐)
2016/08/08 Javascript
浅述节点的创建及常见功能的实现
2016/12/15 Javascript
HTML页面定时跳转方法解析(2种任选)
2016/12/22 Javascript
angularjs实现多张图片上传并预览功能
2017/02/24 Javascript
react native实现往服务器上传网络图片的实例
2017/08/07 Javascript
JScript实现地址选择功能
2017/08/15 Javascript
微信小程序模板(template)使用详解
2018/01/31 Javascript
解决angularjs WdatePicker ng-model的问题
2018/09/13 Javascript
基于better-scroll 实现歌词联动功能的代码
2020/05/07 Javascript
ES6 async、await的基本使用方法示例
2020/06/06 Javascript
[02:27]DOTA2英雄基础教程 莱恩
2014/01/17 DOTA
[23:18]Spirit vs Liquid Supermajor小组赛A组 BO3 第二场 6.2
2018/06/03 DOTA
python定时检查某个进程是否已经关闭的方法
2015/05/20 Python
Python_查看sqlite3表结构,查询语句的示例代码
2019/07/17 Python
利用python实现短信和电话提醒功能的例子
2019/08/08 Python
深入了解Python在HDA中的应用
2019/09/05 Python
Python3实现将一维数组按标准长度分隔为二维数组
2019/11/29 Python
关于Tensorflow使用CPU报错的解决方式
2020/02/05 Python
pandas读取csv文件提示不存在的解决方法及原因分析
2020/04/21 Python
压铸汽车模型收藏家:Diecastmodelswholesale.com
2016/12/21 全球购物
英国天然抗衰老护肤品品牌:Nakin Skin Care
2019/04/16 全球购物
教师个人的自我评价分享
2014/01/02 职场文书
市场开发计划书
2014/05/07 职场文书
奥巴马获胜演讲稿
2014/05/15 职场文书
煤矿安全生产标语
2014/06/06 职场文书
大学生职业生涯十年规划书范文
2014/09/17 职场文书
毕业生自荐材料范文
2014/12/30 职场文书
扬州个园导游词
2015/02/06 职场文书
六一活动主持词
2015/06/30 职场文书
美甲店的创业计划书模板
2019/08/23 职场文书