将函数作为返回值的方法 - Python

有的时候,我们需要将函数作为返回值,以下为代码:

 

def superfunc():
    i = 0
    def wrapper():
        nonlocal i
        i +=1
        return i
    return wrapper

A = superfunc()
print(A(), A(), A())

 

输出:1 2 3 4 5

 

这种将函数作为返回值的方法,如果扩展应用,就可以用来写装饰器的函数。

posted @ 2020-03-27 22:59  Johnthegreat  阅读(421)  评论(0编辑  收藏  举报