python继承和抽象类的实现方法

本文实例讲述了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          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          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

立即学习“Python免费学习笔记(深入)”;

Commission Worker: Sue Jones earned $650.00

Piece Worker: Bob Lewis earned $500.00

Hourly Worker: Karen Price earned $550.00

希望本文所述对大家的Python程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2292388.html

(0)
上一篇 2025年2月28日 01:42:52
下一篇 2025年1月4日 01:13:05

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • python列表操作实例

    本文实例讲述了python列表操作的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:class Node:   “””Single node in a data structure&…

    编程技术 2025年2月28日
    200
  • Python的迭代器和生成器使用实例

    一、迭代器iterators 迭代器仅是一容器对象,它实现了迭代器协议。它有两个基本方法: 1)next方法返回容器的下一个元素 2)__iter__方法返回迭代器自身 迭代器可使用内建的iter方法创建,见例子: 复制代码 代码如下:&g…

    编程技术 2025年2月28日
    200
  • python操作gmail实例

    本文实例讲述了python操作gmail的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:import imaplib, re class pygmail(object):    def __init__(self):…

    编程技术 2025年2月28日
    200
  • Python实现一个简单的MySQL类

    本文实例讲述了python实现一个简单的mysql类。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:#!/usr/bin/env python# -*- coding:utf-8 -*-# Created on 2011-…

    编程技术 2025年2月28日
    200
  • python实现多线程暴力破解登陆路由器功能代码分享

    运行时请在其目录下添加user.txt passwd.txt两文件。否则会报错。程序没有加异常处理。代码比较挫….. 复制代码 代码如下:#coding:utf-8- import base64 import urllib2 i…

    编程技术 2025年2月28日
    200
  • Python基类函数的重载与调用实例分析

    本文实例讲述了python基类函数的重载与调用方法。分享给大家供大家参考。具体分析如下: 刚接触Python语言的时间不长,对于这个语言的很多特性并不是很了解,有很多用法都是还不知道。今天想着写一个Python面向对象编程时的继承中的函数调…

    编程技术 2025年2月28日
    200
  • Python类的专用方法实例分析

    本文实例讲述了python类的专用方法。分享给大家供大家参考。具体分析如下: Python 类可以定义专用方法,专用方法是在特殊情况下或当使用特别语法时由 Python 替你调用的,而不是在代码中直接调用(象普通的方法那样)。 1. __i…

    编程技术 2025年2月28日
    200
  • Python连接mssql数据库编码问题解决方法

    python一直对中文支持的不好,最近老遇到编码问题,而且几乎没有通用的方案来解决这个问题,但是对常见的方法都试过之后,发现还是可以解决的,下面总结了常用的支持中文的编码问题(这些方法中可能其中一个就能解决问题,也可能是多个组合)。 (1)…

    编程技术 2025年2月28日
    200
  • Python中optparse模块使用浅析

    最近遇到一个问题,是指定参数来运行某个特定的进程,这很类似linux中一些命令的参数了,比如ls -a,为什么加上-a选项会响应。optparse模块实现的也是类似的功能,它是为脚本传递命令参数。 使用此模块前,首先需要导入模块中的类Opt…

    2025年2月28日
    200
  • Python解决鸡兔同笼问题的方法

    本文实例讲述了python解决鸡兔同笼问题的方法,分享给大家供大家参考。具体分析如下: 问题描述 一个笼子里面关了鸡和兔子(鸡有 2 只脚,兔子有 4 只脚,没有例外)。已经知道了笼 子里面脚的总数 a,问笼子里面至少有多少只动物,至多有多…

    编程技术 2025年2月28日
    200

发表回复

登录后才能评论