我有以下代码,它可以工作并给出正确的输出:
def msg_before(msg=None):
def actual_decorator(func):
def wrapper(*args, **kwargs):
print(msg if msg is not None else "was none") # original
result = func(*args, **kwargs)
return result
return wrapper
return actual_decorator
@msg_before("this comes before")
def test_func():
print("test")
if __name__ == "__main__":
test_func()
输出:
this comes before test
但是当我像这样更改wrapper
函数时:
def msg_before(msg=None):
def actual_decorator(func):
def wrapper(*args, **kwargs):
msg = msg if msg is not None else "was none" # changed
print(msg) # changed
result = func(*args, **kwargs)
return result
return wrapper
return actual_decorator
我收到以下错误:
Traceback (most recent call last): File "C:/Users/ruohola/Desktop/test.py", line 33, in <module> test_func() File "C:/Users/ruohola/Desktop/test.py", line 19, in wrapper msg = msg if msg is not None else "was none" # changed UnboundLocalError: local variable 'msg' referenced before assignment
在我看来,这两个代码是完全相同的,我只是不了解错误的出处以及为什么在第一个代码中没有发生该错误?