我正在寻找 Python 中的静态值。
我找到了 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
它在函数中使用 python 装饰器作为静态变量。
装饰器
(static_var)
在返回装饰的函数 (foo.counter)
之前初始化静态值 (foo)
。所以我认为它不应该按预期工作,因为每次调用
(static_var)
时,装饰器 foo.counter
都会初始化 foo
。因此,我认为如果 foo() 被调用两次,它应该打印两次
1
foo()
foo()
但它打印
1
和 2
,增加 foo.counter
为什么...?
为什么每次调用 foo 时都没有将
foo.counter
初始化为 0
? 最佳答案
因为:
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
相当于:
foo = static_var("counter", 0)(foo)
注意到
static_var()
实际上被调用了吗?现在遍历你的装饰器;实际上用 import pdb; pdb.set_trace()
单步执行参见:Understanding Python Decorators in 12 easy steps
如果我们在你的装饰器中加入一些
print
(s),看看会发生什么:def static_var(varname, value):
print "1"
def decorate(func):
print "2"
setattr(func, varname, value)
return func
print "3"
return decorate
@static_var("counter", 0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
foo()
foo()
输出:
$ python foo.py
1
3
2
Counter is 1
Counter is 2
关于python - 带有 Python 装饰器的函数中的静态变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30618002/