I want to increase the value by one, and Python has no ++ operator. Consider the following example:
Is __add__ used in this example a bad idea? Is there a better way to write this statement?
Greetings - D
UPDATE
I changed the answer because for ... in ...: v + = calc the solution is much faster than the sum () method. 6 seconds faster than 10,000 iterations, given my settings, but performance difference. Bellow is my test setup:
class Tax(object): def __init__(self, rate): self.rate = rate def calculate_inline(self, cost, other=[]): cost += sum((o.calculate(cost, other[:i]) for i, o in enumerate(other))) return cost * self.rate def calculate_forloop(self, cost, other=[]): for i, o in enumerate(other): cost += o.calculate(cost, other[:i]) return cost * self.rate def test(): tax1 = Tax(0.1) tax2 = Tax(0.2) tax3 = Tax(0.3) Tax.calculate = calculate_inline
With Tax.calculate = calculate_inline problem took 16.9 seconds, and calculate_forloop 10.4 seconds.
source share