Creating a class hierarchy with an abstract base class. : Abstract class : Class PYTHON TUTORIALS


PYTHON TUTORIALS » Class » Abstract class »

 

Creating a class hierarchy with an abstract base class.


class Employee:
   def __init__self, first, last ):
      if self.__class__ == Employee:
         raise NotImplementedError, "Cannot create object of class Employee"
      self.firstName = first
      self.lastName = last

   def __str__self ):
      return "%s %s" self.firstName, self.lastName )

   def _isValidself, value ):
      if value < 0:
         raise ValueError, "Attribute value (%s) must be positive" % value
      else:
         return value

   def earningsself ):
      raise NotImplementedError, "Cannot call abstract method"

class BossEmployee ):
   def __init__self, first, last, salary ):
      Employee.__init__self, first, last )
      self.weeklySalary = self._isValidfloatsalary ) )

   def earningsself ):
      return self.weeklySalary

   def __str__self ):
      return "%20s: %s" "Boss", Employee.__str__self ) )

class DeveloperEmployee ):
   def __init__self, first, last, salary, commission, quantity ):
      Employee.__init__self, first, last )
      self.salary = self._isValidfloatsalary ) )
      self.commission = self._isValidfloatcommission ) )
      self.quantity = self._isValidquantity )

   def earningsself ):
      return self.salary + self.commission * self.quantity

   def __str__self ):
      return "%20s: %s" "Commission Worker", Employee.__str__self ) )

class TesterEmployee ):
   def __init__self, first, last, wage, quantity ):
      Employee.__init__self, first, last )
      self.wagePerPiece = self._isValidfloatwage ) )
      self.quantity = self._isValidquantity )

   def earningsself ):
      return self.quantity * self.wagePerPiece

   def __str__self ):
      return "%20s: %s" "Piece Worker", Employee.__str__self) )

class ProgrammerEmployee ):
   def __init__self, first, last, wage, hours ):
      Employee.__init__self, first, last )
      self.wage = self._isValidfloatwage ) )
      self.hours = self._isValidfloathours ) )

   def earningsself ):
      if self.hours <= 40:
         return self.wage * self.hours
      else:
         return 40 * self.wage + self.hours - 40 * self.wage * 1.5

   def __str__self ):
      return "%20s: %s" "Hourly Worker",Employee.__str__self ) )

# main program
employees = Boss"A""B"8.00 ),
              Developer"C""D"2.03.0150 ),
              Tester"E""F"2.5200 ),
              Programmer"G""H"13.7540 ) ]

for employee in employees:
   print "%s earned $%.2f" employee, employee.earnings() )



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .


PYTHON TUTORIALS

 Navioo Class
» Abstract class