View Single Post
Old Jan 30th, 2007, 9:52 AM   #6
ptmcg
Newbie
 
Join Date: Aug 2005
Location: Austin, TX
Posts: 15
Rep Power: 0 ptmcg is on a distinguished road
A Percent class for doing percentage arithmetic

Python's ability to emulate numeric types makes it easy to "extend" Python with some interesting behavior. Here's a Percent class that allows you to write code like: saleprice = origprice - discount, where origprice is a number, and discount is a class instance that computes the actual discount based on the value of origprice.

You could do the same thing with a variable called markup as in markup=Percent(10) and then compute retailprice = wholesaleprice + markup.

-- Paul

class Percent(object):
    def __init__(self,pctval):
        self.pct = pctval
        self.pctFloat = pctval/100.0
        
    def __mul__(self,other):
        if isinstance(other,Percent):
            return Percent(self.pct*other.pctFloat)
        else:
            return other*self.pctFloat
            
    def __rmul__(self,other):
        return self * other

    def __radd__(self,other):
        if isinstance(other,Percent):
            return Percent(self.pct+other.pct)
        else:
            return other + self*other

    def __rsub__(self,other):
        if isinstance(other,Percent):
            return Percent(other.pct-self.pct)
        else:
            return other - self*other

    def __str__(self):
        if int(self.pct)==self.pct:
            return "%d%%" % self.pct
        else:
            return "%f%%" % self.pct

discount = Percent(20)
print discount

print 35 - discount
print 50 - discount
print 100 - discount

origprice = 35.00
saleprice = origprice - discount
print saleprice
Prints:
20%
28.0
40.0
80.0
28.0
ptmcg is offline   Reply With Quote