Skip to content

Latest commit

 

History

History
29 lines (25 loc) · 776 Bytes

21.md

File metadata and controls

29 lines (25 loc) · 776 Bytes
@author jackzhenguo
@desc 
@date 2019/2/20

21 nonlocal用于内嵌函数中

关键词nonlocal常用于函数嵌套中,声明变量i为非局部变量; 如果不声明,i+=1表明i为函数wrapper内的局部变量,因为在i+=1引用(reference)时,i未被声明,所以会报unreferenced variable的错误。

def excepter(f):
    i = 0
    t1 = time.time()
    def wrapper(): 
        try:
            f()
        except Exception as e:
            nonlocal i
            i += 1
            print(f'{e.args[0]}: {i}')
            t2 = time.time()
            if i == n:
                print(f'spending time:{round(t2-t1,2)}')
    return wrapper
[上一个例子](20.md) [下一个例子](22.md)