Implementation of python inheritance and abstract classes

Source: Internet
Author: User
This article mainly introduces the implementation methods of python inheritance and abstract classes. The example analyzes the class inheritance of Python and the definition and usage skills of abstract classes, which has some reference value, for more information about how to implement python inheritance and abstract classes, see the example in this article. Share it with you for your reference.

The specific implementation method is as follows:

The code is as follows:

#! /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" % (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 "% 17 s: % 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 "% 17 s: % 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 "% 17 s: % 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 "% 17 s: % 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 ())

The output result is as follows:

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

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.