Simulate static variables in python with closures

这一生的挚爱 提交于 2020-01-16 01:21:06

问题


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.


回答1:


Yes, you can

def f(a):
    def inner(h, a):
        print h+a
        return lambda (x): inner(h+1, x)
    return inner(1, a)

example

g = f(0) # +1
g = g(0) # +2
g = g(0) # +3

f(0) # +1
g(0) # +4
g(0) # +4

prints

1
2
3
1
4
4

Q.E.D.




回答2:


In python 3, you can do this:

>>> 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>

Previous versions required faking it:

>>> 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>
>>> 

(ETA: I guess I misinterpreted part of the question, since it seems you want the function returned by f (and that returns itself) to take the argument, but that's a trivial change.)



来源:https://stackoverflow.com/questions/8175323/simulate-static-variables-in-python-with-closures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!