Why aren't python nested functions called closures?

后端 未结 8 796
情歌与酒
情歌与酒 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.

提交回复
热议问题