Python中的闭包

参考

In [68]: def greeting_conf(prefix):
    ...:     def greeting(name):
    ...:         print(prefix,name)
    ...:     return greeting
    ...:

In [69]: mygree=greeting_conf("Good Mornng")

In [71]: t=mygree("小静")
Good Mornng 小静

In [84]: mygree.__name__
Out[84]: 'greeting'

In [85]: id(mygree)
Out[85]: 1827000076760

In [86]: mygree2=greeting_conf("good afternoon")

In [87]: mygree2.__name__
Out[87]: 'greeting'

In [88]: id(mygree2)
Out[88]: 1827002460904

In [89]: def test(a):
    ...:     print(a)

In [90]: test1=test(1)
1

In [91]: test2=test(2)
2

In [92]: test1.__name__


In [93]: id(test1)
Out[93]: 1595913440

In [94]: id(test2)
Out[94]: 1595913440
   

Python中怎么创建闭包

在Python中创建一个闭包可以归结为以下三点:
1.闭包函数必须有内嵌函数
2. 内嵌函数需要引用该嵌套函数上一级namespace中的变量
3. 闭包函数必须返回内嵌函数

你可能感兴趣的:(python,基础)