View Single Post
Old Jan 31st, 2007, 5:34 AM   #13
ptmcg
Newbie
 
Join Date: Aug 2005
Location: Austin, TX
Posts: 15
Rep Power: 0 ptmcg is on a distinguished road
Just a couple more examples:

fica = Percent(7)
fedtax = Percent(15)
medicare = Percent(3)
deductions = fica + fedtax + medicare
gross = 100000
net = gross - deductions
print net # answer: 75000

wholesale = 10
markup = Percent(35)
retail = wholesale + markup
print retail # answer: 13.5

yearlyApprec = Percent(8)
basis = 10000
newbasis = basis + yearlyApprec + yearlyApprec + yearlyApprec
print newbasis # answer: 12597.12

I still think this is rather pretty, the kind of thing that DSL's are made of. Imagine applying this same technique (emulating numeric types using _add_, _radd_, etc.) to applications such as:
  • adding resistors in a network
  • adding temperature of various quantities of water
  • adding vectors
  • adding physical bodies (with gravity, momentum) to a dynamic model
Yet I can certainly sympathize with the maintainer who, trying to debug the above code later wonders, "where the hell do they calculate the markup?".

Still, here is what the OP started with:
Tolerance = 0.05 * Energy
Energy = Energy - Tolerance

Of course, this is probably the simplest and most direct implementation of subtracting 5% of something from something else. Why was the OP asking the question in the first place? The Percent class illustrates an atypical object capability provided by Python, to be able to define an object that can take additional information from its arithmetic context to modify its behavior. With Percent, the OP can define
Tolerance = Percent(5)
completely independently from what the tolerance is to be calculated on, and then later apply it to Energy using
Energy = Energy - Tolerance
or even just
Energy -= Tolerance

So is this Percent class silly overkill for something so mundane as calculating a percentage? Perhaps. But I find Python's numeric type emulation capabilities to be quite interesting, and it seemed a decent fit and a simple example to the OP's question.

Last edited by ptmcg; Jan 31st, 2007 at 6:18 AM. Reason: after re-reading the original post; added one more example
ptmcg is offline   Reply With Quote