# Python闭包和装饰器
############# 闭包 ##############
'''
1. 一个外层函数,内嵌一个内层函数;
2. 内层函数使用外层函数的参数;
3. 外层函数将内层函数作为返回值返回
'''
# 外层函数
def outer(msg):
# 内层函数
def inner():
# 内层函数使用外层函数的参数
print(msg)
# 将内层函数作为返回值返回
return inner
inner = outer('hello world')
inner() # 结果打印:hello world
# 在这个过程中,调用完outer()之后,将变量msg保留了下来,在inner()调用时可以继续使用
############# 装饰器 ##############
'''
1. 装饰器的本质就是闭包,只不过外层函数的参数就是 “要装饰的那个函数”;
'''
# 定义一个装饰器decoration
def decoration(func):
def inner():
# 在前面添加新的功能
print('before new function!')
# 调用原本的函数
func()
# 在后面添加新的功能
print('after new function!')
return inner
# 定义函数hello
def hello():
print('hello')
# 用装饰器decoration装饰函数hello
hello = decoration(hello)
hello()
'''
结果打印:
before new function!
hello
after new function!
'''
# 用装饰器decoration来装饰函数的另一种写法,效果是一样的
@decoration
def hello_2():
print('hello_2')
hello_2()
'''
结果打印:
before new function!
hello_2
after new function!
'''