Uses __add__ in Python by mistake?

I want to increase the value by one, and Python has no ++ operator. Consider the following example:

# In a method called calculate(self, basecost, othertaxes=None) # Returns the value of the tax (self) applied to basecost in relation to previous taxes i = -1 basecost += sum((tax.calculate(basecost, othertaxes[:i.__add__(1)]) for tax in othertaxes)) 

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 # or calculate_forloop tax1.calculate(100.0, [tax2, tax3]) if __name__ == '__main__': from timeit import Timer t = Timer('test()', 'from __main__ import test; gc.enable()') print t.timeit() 

With Tax.calculate = calculate_inline problem took 16.9 seconds, and calculate_forloop 10.4 seconds.

+4
source share
4 answers

If I read this right:

 for i,tax in enumerate(othertaxes): basecost += tax.calculate(basecost,othertaxes[:i]) 
+3
source

It seems to be:

 basecost += sum((tax.calculate(basecost, othertaxes[:i]) for i,tax in enumerate(othertaxes)) 
+9
source

In Python, integers are not changed (are not float, booleans or string).

You cannot change the value of i unless you write i + = 1. i. add (1) does not change the value of i, it just returns a new integer equal to (i + 1).

+1
source

Usually you use lambda x: x+1 instead of __add__

0
source

Source: https://habr.com/ru/post/1348207/


All Articles