在Python上使用__add__是个坏主意吗?

Dim*_*try 4 python

我希望将值递增1,Python没有++运算符.请考虑以下示例:

# 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))
Run Code Online (Sandbox Code Playgroud)

在这个例子中使用__add__是个坏主意吗?有没有更好的方式来写这个陈述?

干杯 - D.


UPDATE

我已经改变了答案,因为for ... in ...:v + = calc解决方案比sum()方法快得多.鉴于我的设置,在10000次迭代中快6秒,但性能差异就在那里.贝娄是我的测试设置:

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()
Run Code Online (Sandbox Code Playgroud)

有了Tax.calculate = calculate_inline,这个问题用了16.9秒,用calculate_forloop了10.4秒.

Joc*_*zel 9

似乎是这样的:

basecost += sum((tax.calculate(basecost, othertaxes[:i]) 
                      for i,tax in enumerate(othertaxes))
Run Code Online (Sandbox Code Playgroud)