跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI
@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

上一个例子 下一个例子

大家在看

京ICP备20031037号-1 | AI之家 | AI资讯 | Python200 | 数据分析