python - 用闭包模拟python中的静态变量

标签 python static closures

是否可以在 python 中编写一个函数,它接受一个参数 a 并打印 h+a 的结果,其中 h 是一个局部变量。然后它应该返回自身,h 增加 1。

最佳答案

在 python 3 中,你可以这样做:

>>> def f(a):
...     h = 1
...     def inner():
...             nonlocal h
...             print(a+h)
...             h += 1
...             return inner
...     return inner
... 
>>> g = f(3)  
>>> g = g()
4
>>> g = g()
5 
>>> g = g()
6
>>> g()()()
7 
8
9
<function inner at 0xb71bcd6c>

以前的版本需要伪造它:

>>> def f(a):
...     h = [1]
...     def inner():
...             print a + h[0]
...             h[0] += 1
...             return inner
...     return inner
... 
>>> f(3)()()()
4  
5
6
<function inner at 0x10041f050>
>>> 

(预计到达时间:我想我误解了部分问题,因为您似乎希望 f 返回的函数(并返回自身)接受参数,但这是一个微不足道的变化。)

关于python - 用闭包模拟python中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8175323/

相关文章:

ios - 在 iOS/iPhone SDK 中控制第三方符号的导出

php静态函数

javascript - javascript函数中的第二组括号调用了什么?

python - 我不理解 python 中的 sum(iterable[, start])

python - __unicode__ 在获取字符串表示时未调用 Django/Python 项目中的某些对象

java - "overriding"main 在 Java 中有什么作用?

jquery - 在闭包中使用 'this'

jquery - 与 jQuery grunt 脚本相比,Jammit 对 jQuery 1.9.1 的压缩效果很差(145k vs 93k)

python - 如何在数据帧中的字符串中查找数字并使用千位分隔符重新格式化该数字?

python - datetime.timedelta 返回意外结果?