什么是python闭包好?

Ale*_*lex -5 python closures python-3.x

我理解python闭包的技术定义:让它具体化.

def foo(x):
    def bar(y):
        print(x+y)
    return bar
Run Code Online (Sandbox Code Playgroud)

在这个例子x中将受到约束bar.但这些东西实际上有什么用呢?也就是说,在上面的玩具示例中,可以轻松地编写

def bar(x,y):
    print(x+y)
Run Code Online (Sandbox Code Playgroud)

我想知道使用闭包的最佳用例,而不是例如向函数添加额外的参数.

Oli*_*çon 5

我认为最常用的闭包示例是使用装饰器缓存函数.

def cache_decorator(f):

    cache = {}

    def wrapper(*args):
        if args not in cache:
            cache[args] = f(*args)

        return cache[args]

    return wrapper

@cache_decorator
def some_function(*args):
    ...
Run Code Online (Sandbox Code Playgroud)

这样cache就无法从任何地方引用,因为您不希望用户篡改它.