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实现带百分比的进度条
Jun 28 Python
Python获取当前函数名称方法实例分享
Jan 18 Python
Python动态生成多维数组的方法示例
Aug 09 Python
Python pymongo模块常用操作分析
Sep 01 Python
Python实现注册、登录小程序功能
Sep 21 Python
python3爬虫获取html内容及各属性值的方法
Dec 17 Python
Python安装tar.gz格式文件方法详解
Jan 19 Python
Python turtle画图库&amp;&amp;画姓名实例
Jan 19 Python
Python3 xml.etree.ElementTree支持的XPath语法详解
Mar 06 Python
Python检测端口IP字符串是否合法
Jun 05 Python
pytorch加载语音类自定义数据集的方法教程
Nov 10 Python
Python数据分析之pandas函数详解
Apr 21 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
example2.php
2006/10/09 PHP
实用函数10
2007/11/08 PHP
php把数据表导出为Excel表的最简单、最快的方法(不用插件)
2014/05/10 PHP
php 数组处理函数extract详解及实例代码
2016/11/23 PHP
php获取给定日期相差天数的方法分析
2017/02/20 PHP
PHP 应用容器化以及部署方法
2018/02/12 PHP
解决在laravel中auth建立时候遇到的问题
2019/10/15 PHP
javascript 最常用的10个自定义函数[推荐]
2009/12/26 Javascript
jquery获得option的值和对option进行操作
2013/12/13 Javascript
js预加载图片方法汇总
2015/06/15 Javascript
谈谈javascript中使用连等赋值操作带来的问题
2015/11/26 Javascript
JS中的数组方法笔记整理
2016/07/26 Javascript
JS访问DOM节点方法详解
2016/11/29 Javascript
es6学习笔记之Async函数的使用示例
2017/05/11 Javascript
angular2系列之路由转场动画的示例代码
2017/11/09 Javascript
详解vue-cli下ESlint 配置说明
2018/09/03 Javascript
JS实现滚动条触底加载更多
2019/09/19 Javascript
python中实现精确的浮点数运算详解
2017/11/02 Python
django用户注册、登录、注销和用户扩展的示例
2018/03/19 Python
python字典值排序并取出前n个key值的方法
2018/10/17 Python
python程序封装为win32服务的方法
2021/03/07 Python
pandas通过字典生成dataframe的方法步骤
2019/07/23 Python
关于Python中的向量相加和numpy中的向量相加效率对比
2019/08/26 Python
爬虫代理池Python3WebSpider源代码测试过程解析
2019/12/20 Python
Pandas时间序列基础详解(转换,索引,切片)
2020/02/26 Python
使用python3 实现插入数据到mysql
2020/03/02 Python
Python爬虫程序架构和运行流程原理解析
2020/03/09 Python
Python matplotlib绘制图形实例(包括点,曲线,注释和箭头)
2020/04/17 Python
Django 解决由save方法引发的错误
2020/05/21 Python
摩托车和ATV零件、配件和服装的首选在线零售商:MotoSport
2017/12/22 全球购物
生产文员岗位职责
2014/04/05 职场文书
保证书范文大全
2014/04/28 职场文书
创建青年文明号材料
2014/05/09 职场文书
绿色环保家庭事迹材料
2014/08/31 职场文书
小学体育队列队形教学反思
2016/02/16 职场文书
大学生军训心得体会5篇
2019/08/15 职场文书