<p>约翰你应该读<a href="http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/" rel="nofollow">this</a>。在python中,变量不是对象。你的问题是“是否有可能让decorator在运行时获得一个变量的值”,因为python的作用域规则是没有意义的。decorator函数通常无权访问定义<code>state</code>的范围。不过,有几种方法可以让你得到想要的行为。你知道吗</p>
<p>在不知道你想做什么的具体情况下,这里有两个可能有用的方法。第一个使用闭包:</p>
<pre><code>state = None
def with_closure(f):
def helper(*args, **kwargs):
# state is in scope for this function
print "Current state is: {}.".format(state)
return f(*args, **kwargs)
return helper
@with_closure
def foo():
return "something"
</code></pre>
<p>或者可以制作一个对象来跟踪状态:</p>
<pre><code>class StateHolder:
def set_state(self, state):
self.state = state
def with_state_object(state_object):
def decorator(f):
def helper(*args, **kwargs):
print "Current state is: {}.".format(state_object.state)
return f(*args, **kwargs)
return helper
return decorator
global_state = StateHolder()
global_state.set_state("some state")
@with_state_object(global_state)
def foo():
return "something"
</code></pre>