使用闭包在python中模拟静态变量 [英] Simulate static variables in python with closures
本文介绍了使用闭包在python中模拟静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在python中编写一个函数,该函数接受参数a并输出h + a的结果,其中h是局部变量。然后它应该返回自身,并且h增加一个。
Is it possible to write a function in python, which takes an argument a and prints the result of h+a where h is a local variable. Then it should return itself, with h increased by one.
推荐答案
是的,您可以
def f(a):
def inner(h, a):
print h+a
return lambda (x): inner(h+1, x)
return inner(1, a)
示例
g = f(0) # +1
g = g(0) # +2
g = g(0) # +3
f(0) # +1
g(0) # +4
g(0) # +4
打印
1
2
3
1
4
4
QED
这篇关于使用闭包在python中模拟静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文