擅长:python、mysql、java
<p>您可以使用<a href="https://www.python.org/dev/peps/pep-3104/" rel="nofollow noreferrer">^{<cd1>}</a>创建一个闭包,使其可编辑(仅限python 3.x)。下面是一个递归函数的示例,用于计算列表的长度。</p>
<pre><code>def recursive_len(l):
res = 0
def inner(l2):
nonlocal res
if l2:
res += 1
inner(l2[1:])
inner(l)
return res
</code></pre>
<p>或者,可以为函数本身指定一个属性。使用<a href="https://stackoverflow.com/a/3209862/3816975">here</a>中的技巧:</p>
<pre><code>def fn(self):
self.number_of_times += 1
fn.func_defaults = (fn,)
fn.number_of_times = 0
fn()
fn()
fn()
print (fn.number_of_times)
</code></pre>