I was looking for about static value in Python.
And I found this.
def static_var(varname, value):
def decorate(func):
setattr(func, varname, value)
return func
return decorate
@static_var("counter", 0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
It is using python decorator for static variable in a function.
The decorator(static_var) initialize static value(foo.counter) before returning the function(foo) decorated.
So I think it should not work as expected, because decorator(static_var) initialize foo.counter every time when foo is called.
As a result, I think if foo() is called two times, it should print 1 two times
foo()
foo()
But It prints 1 and 2, increasing foo.counter
Why...?
Why isn't foo.counter initialized to 0 every time when foo is called?