[英]Is using __add__ in Python on an int a bad idea?
I'm looking to increment a value by one and Python does not have the ++ operator. 我希望将值递增1并且Python没有++运算符。 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 the use of __add__ in this example a bad idea? 在这个例子中使用__add__是个坏主意吗? Is there a better way to write this statement?
有没有更好的方式来写这个陈述?
Cheers - D 干杯 - D.
UPDATE UPDATE
I have changed the answer because the for ... in ...: v += calc solution is much faster than the sum() method. 我已经改变了答案,因为for ... in ...:v + = calc解决方案比sum()方法快得多。 6 seconds faster over 10000 iterations given my setup but the performance difference is there.
鉴于我的设置,在10000次迭代中快6秒,但性能差异就在那里。 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
, the problem took 16.9 seconds, with calculate_forloop
, it took 10.4 seconds. 使用
Tax.calculate = calculate_inline
,问题需要16.9秒,使用calculate_forloop
,需要10.4秒。
Seems to be this: 似乎是这样的:
basecost += sum((tax.calculate(basecost, othertaxes[:i])
for i,tax in enumerate(othertaxes))
If I'm reading that right: 如果我正在读正确的话:
for i,tax in enumerate(othertaxes):
basecost += tax.calculate(basecost,othertaxes[:i])
In Python, integers are not mutable (neither are floats, booleans or strings). 在Python中,整数不可变(浮点数,布尔值或字符串都不是)。
You cannot change the value of i unless you write i += 1. i. 除非你写i + = 1,否则你不能改变i的值。 add (1) does not change the value of i, it just returns a new integer which equals (i+1).
add (1)不会改变i的值,它只返回一个等于(i + 1)的新整数。
你通常会做一个lambda x: x+1
而不是使用__add__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.