【发布时间】:2015-03-12 11:45:54
【问题描述】:
这是我上一个问题Change an attribute of a function inside its own body的延续。
如果我包装了一个函数,以便使用以下装饰器计算它被调用的次数:
def keep_count(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
f(*args, **kwargs)
wrapped_f.count += 1
wrapped_f.count = 0
return wrapped_f
然后我想用别的东西再次包装它:
def decorator2(fn):
@wraps(fn)
def fn_wrapper(*args, **kwargs):
if my_condition(fn):
fn(*args, **kwargs)
return fn_wrapper
test_f = decorator2(test_f)
我不能再像我希望的那样访问函数的count 属性。
count 属性的当前值通过@wraps(fn) 复制,但如果我再次调用该函数,计数将在原始函数内递增,但新值不会复制到新修饰函数。
>>> test_f()
() {}
>>> test_f.count
1
>>> test_f = decorator2(test_f)
>>> test_f.count # The 1 gets copied here
1
>>> test_f() # Only the inner function's count increments...
() {}
>>> test_f.count # Still one, tho it should be two
1
有什么解决办法吗? 比如“不断地”重新包装,或者更好的东西?
【问题讨论】:
-
@MartijnPieters 更新了...是的,我知道这一点,我基本上是在问如何分享它们:P
标签: python python-3.x decorator wrapper python-decorators