Why aren't python nested functions called closures?

后端 未结 8 628
情歌与酒
情歌与酒 2020-11-22 05:37

I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called nested functions instead of closures<

相关标签:
8条回答
  • 2020-11-22 06:25
    def nested1(num1): 
        print "nested1 has",num1
        def nested2(num2):
            print "nested2 has",num2,"and it can reach to",num1
            return num1+num2    #num1 referenced for reading here
        return nested2
    

    Gives:

    In [17]: my_func=nested1(8)
    nested1 has 8
    
    In [21]: my_func(5)
    nested2 has 5 and it can reach to 8
    Out[21]: 13
    

    This is an example of what a closure is and how it can be used.

    0 讨论(0)
  • 2020-11-22 06:26

    Python 2 didn't have closures - it had workarounds that resembled closures.

    There are plenty of examples in answers already given - copying in variables to the inner function, modifying an object on the inner function, etc.

    In Python 3, support is more explicit - and succinct:

    def closure():
        count = 0
        def inner():
            nonlocal count
            count += 1
            print(count)
        return inner
    

    Usage:

    start = closure()
    start() # prints 1
    start() # prints 2
    start() # prints 3
    

    The nonlocal keyword binds the inner function to the outer variable explicitly mentioned, in effect enclosing it. Hence more explicitly a 'closure'.

    0 讨论(0)
提交回复
热议问题