闭包函数:就是一个方法下面嵌套一个方法,
如何判断是否是闭包函数:
1、第二层或者以上层函数 是否引用或者返回上一层的参数:引用了就是闭包,不引用则不是
2、判断字段标准就是 打印出 函数.closure
下面可以理解不是闭包函数
def info():
code = 'python'
def log():
# print(code)
pass
print(log.__closure__) # 为 None
return log
if __name__ == '__main__':
a = info()
a()
再举个例子:
def info():
code = 'python'
def log():
print(code) # python
print(log.__closure__) # 为 (<cell at 0x000002E72700FE80: str object at 0x000002E726C18030>,)
return log
if __name__ == '__main__':
a = info()
a()
打印出来的函数.__closure__yo 存在对象,那这就是一个闭包函数。
再举个例子:上难度:闭包函数:
def info():
a = 'python'
b = '000'
def log():
c = '111'
print(a + b)
def code():
print(a + b + c)
print(code.__closure__)
return code
return log
if __name__ == '__main__':
logs = info()
code = logs()
code()
运行结果:
python000
python000111
(<cell at 0x0000013E2A8EFFA0: str object at 0x0000013E2A848030>, <cell at 0x0000013E2A8EFEE0: str object at 0x0000013E2A848430>, <cell at 0x0000013E2A8EFEB0: str object at 0x0000013E2A8B7F70>, <cell at 0x0000013E2A8EFDC0: function object at 0x0000013E2A9711B0>)