Scope of variables in function factories

I was wondering about the scope of the variable a in the following Python snippet,

# ============================
def get_plotter():
    def get_a():
        return a
    a = 3.14
    return get_a
# ============================
if __name__ == '__main__':
    f = get_plotter()
    print f()
# ============================

The output is 3.14 , but looking at the code I would have expected a to go out of scope as soon as get_plotter() terminates, effectively leaving an undefined something.

Is it just volatile memory contents that are printed here? What's going on?


This works because of closures, or "functions with data attached", and is explained well here

https://stackoverflow.com/a/141426/735204

链接地址: http://www.djcxy.com/p/51126.html

上一篇: 我该如何理解Python中这个深度绑定的例子?

下一篇: 函数工厂中变量的范围