我创建了一个简单的装饰器,它接收一个参数(使用函数而不是一个类),当发生一些奇怪的事情时:添加一行代码会中断前一行的执行。
这是代码:
def my_decorator(sublabel):
def duration_wrapper(f):
print sublabel
# Uncommenting this code will break the previous line - why?
# if sublabel is None:
# sublabel = f.func_name
def wrapped_function(*args, **kwargs):
return f(*args, **kwargs)
return wrapped_function
return duration_wrapper
@my_decorator('me')
def myf(): pass
myf()
取消注释这些代码行会导致此异常:
Traceback (most recent call last):
File "test.py", line 16, in <module>
@my_decorator('me')
File "test.py", line 4, in duration_wrapper
print sublabel
UnboundLocalError: local variable 'sublabel' referenced before assignment
谁能解释为什么取消注释那两行代码会破坏它?