在Python中对int使用__add__是个坏主意吗?
我想把一个值加一,但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))
在这个例子中使用__add__是不是个坏主意?有没有更好的写法呢?
谢谢 - D
更新
我改变了我的回答,因为用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()
使用Tax.calculate = calculate_inline
时,问题花了16.9秒,而用calculate_forloop
时,只花了10.4秒。
4 个回答
1
在Python中,整数是不可变的(浮点数、布尔值和字符串也是不可变的)。
你不能直接改变变量i的值,除非你写成i += 1。使用i.add(1)并不会改变i的值,它只是返回一个新的整数,这个新整数的值是(i+1)。
9
看起来是这个:
basecost += sum((tax.calculate(basecost, othertaxes[:i])
for i,tax in enumerate(othertaxes))
3
如果我理解得没错:
for i,tax in enumerate(othertaxes):
basecost += tax.calculate(basecost,othertaxes[:i])