def __isPercent__(obj):
"""Check if object is an percent instance."""
if not isinstance(obj, Percent):
raise AttributeError, 'percent expected, %s found' % type(obj) # END __isPercent__
def __isNatural__(obj):
"""Check if object is an positive integer instance."""
if not isinstance(obj, int):
raise AttributeError, 'integer expected, %s found' % type(obj) elif isinstance(obj, int) and obj < 0:
raise AttributeError, 'natural expected'
# END __isInteger__
##################################################
class Percent(float):
def __init__(self, value=-1):
"""Create a percentage.
@param value: value of the percentage
@type value: integer or float between 0 and 100"""
if value < 0 or value > 100:
raise ValueError, 'incorrect value %s' % str(value)
float.__init__(self, round(value, 2))
# END __init__
def __add__(self, other=None):
"""Add a percentage to another.
@param other: percentage to add
@type other: instance of the Percent class"""
__isPercent__(other)
return Percent(float.__add__(self, other)) # END __add__
def __sub__(self, other=None):
"""Substract a percentage from another.
@param other: percentage to substract
@type other: instance of the Percent class"""
__isPercent__(other)
return Percent(float.__sub__(self, other)) # END __sub__
def __mul__(self, other=None):
"""Multiply a percentage by an int.
@param other: factor
@type other: integer"""
__isNatural__(other)
return Percent(float.__mul__(self, other)) # END __mul__
def __floordiv__(self, other=None):
"""Divide a percentage by an int.
@param other: denominator
@type other: integer"""
__isNatural__(other)
return Percent(float.__floordiv__(self, other)) # END __floordiv__
def __coerce__(self, other=None):
"""Handling different operand types is left to the operation."""
return (self, other)
# END __coerce__
def getUnitar(self):
"""Return the fractional value of the percentage."""
return round(self / 100, 2)
# END getUnitar
# END Percent
|