【发布时间】:2015-08-19 14:48:27
【问题描述】:
我有一个类似的案例-
flag = True
print "Before All things happened, flag is", flag
def decorator(*a):
def real_decorator(function):
def wrapper(*args, **kwargs):
global flag
flag = False
print "just in real decorator before function call i.e. before", function.__name__
print "flag is " , flag
function(*args, **kwargs)
print "In real decorator after function call i.e. after", function.__name__
flag = True
print "flag is ", flag
return wrapper
return real_decorator
@decorator()
def subtota():
print "in subtota"
print "flag is" , flag
@decorator()
def print_args(*args):
print "in print args"
for arg in args:
print arg
print "flag is ", flag
subtota()
print "we do want flag to be false here, after subtota"
print "but, flag is ", flag
print_args("bilbo", "baggins")
print "after All things happended flag is ", flag
输出是
Before All things happened, flag is True
just in real decorator before function call i.e. before print_args
flag is False
in print args
bilbo
baggins
flag is False
just in real decorator before function call i.e. before subtota
flag is False
in subtota
flag is False
In real decorator after function call i.e. after subtota
flag is True
we do want flag to be false here, after subtota
but, flag is True
In real decorator after function call i.e. after print_args
flag is True
after All things happended flag is True
在这里,我不想更改subtota() 之后的标志值,或者我们可以说,我们希望保持每个函数的行为彼此独立。
我们怎样才能做到这一点?
PS - 无法避免使用模块级全局变量flag。
EDIT-期望的行为- 只有在最上面的函数执行后,标志才应该为假。
【问题讨论】:
-
那么您希望在哪里输出呢?我已经尝试回答了,但是添加对预期行为的描述会很有帮助。
标签: python python-2.7 decorator python-decorators globals