node
被传递给上下文管理器,我想在开始时锁定它,然后做一些工作,最后解锁节点。在cd1{cd1>执行过程中,{do}是如何被更新的?在
这段代码在Python2.7中运行
from contextlib import contextmanager
@contextmanager
def call(begin, end, *args, **kwargs):
begin(*args, **kwargs)
try:
yield
finally:
end(*args, **kwargs)
def lockFunc(*args):
print 'in lockFunc'
print 'lock %s' %args[0]
def unlockFunc(*args):
print 'in unlockFunc'
print 'unlock %s' %args[0]
node = 'old-node'
with call(lockFunc, unlockFunc, node):
print 'in with'
# update node value here
node = 'new-node'
但结果是
^{pr2}$我怎样才能让unlockFunc
知道node
已更改。在
编辑:我尝试过使node
成为一个列表,但这不起作用。在
编辑2: 我试着用一个列表,它是这样工作的。在
node = ['old-node']
with call(lockFunc, unlockFunc, node):
print 'in with'
node[0] = 'new-node'
我找到了更好的解决办法。在
{{cd2>所引用的对象{cd1>没有改变^的问题。在
相反,您需要告诉对象要更改,并且只能对可变对象执行此操作;字符串不是可变的。一个列表可以,但我认为一个类可能更清楚一些:
产生
^{pr2}$(Ubuntu 14.04,Python 2.7.6)
相关问题 更多 >
编程相关推荐