擅长:python、mysql、java
<p>保持自身状态的函数?我会这样做:</p>
<pre><code>class func:
# can behave as a function, but can also hold its own value
def __init__(self, value=0):
self.value = value
# this function is the actual 'function' that is called each time
def __call__(self, arg):
self.value += arg
return self.value
fns = []
for i in range(5):
# create new function, and give it a starting value of i
fn = func(i)
fns += [fn]
for fn in fns:
print( fn(0) )
</code></pre>
<p>结果是<code>0 1 2 3 4</code></p>