- 闭包函数必要条件
- 简单例子
- 一些说明
- 应用
闭包函数必要条件
- 必须返回一个函数对象
- 闭包返回函数必须引用外部变量(一般不能是全局变量。可以是父函数传入参数、变量)
- 装饰器就是一种闭包
简单例子
def fun(a): b = 12 def doit(x): print(a+b-x) return doit func = fun(2) func(4) # a(2) + b(12) - x # 2 + 12 - 4 = 10 print(func.__closure__) # Output ''' 10 (| , | ) ''' |
一些说明
- __closure__ 属性返回值为元组,具体为闭包引用的外部变量
- 如果主函数的内函数不引用外部变量,或者主函数不返回函数对象,那么不存在闭包,__closure__ 属性为 None
- 闭包返回时,变量就已经确定,形成了封闭对象。闭包可以保存运行环境
| - 函数也可以定义属性 | ||
| def fun(): x = 12 fun.id = 12 print(fun.id) | 输出:12 | |
| - 自有属性 | ||
| __doc__ | __hash__ | __repr__ |
| __defaults__ tuple | __name__ String | |
import test def fun(): import time
应用
def person(name):
def sayit(words):
print(f' {name}: {words}')
return sayit
Fry = person('Fry')
Bender = person('Bender')
Fry('Good news everyone!')
Bender('Bite my shiny metal ass!')
# Output
'''
Fry: Good news everyone!
Bender: Bite my shiny metal ass!
'''



