1、闭包
1.1 通过函数嵌套,函数的返回值是函数对象
def func_closure():
def get_message(message):
print('Got a message: {}'.format(message))
return get_message
send_message = func_closure()
send_message('hello world')
输出:
Got a message: hello word
1.2 内部函数直接可以使用外部函数提供的变量
def line_conf(a, b):
def line(x):
return a*x + b
# 返回闭包结果
return line
# 传递外部函数参数
line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
# 传入内部函数参数5
print(line1(5))
print(line2(5))
输出:
6
25
2、装饰器
2.1 通过装饰器函数,给原函数进行功能扩展,即已经实现的功能代码不被修改的前提下对其他函数进行功能扩展
def my_decorator(func):
def wrapper():
print('wrapper of decorator')
func()
return wrapper
# @my_decorator相当于greet = my_decorator(greet)
@my_decorator
def greet():
print(hello world)
greet()
输出:
wrapper of decorator
hello world
2.2 带有参数的装饰器
1.可以给装饰器函数的内部函数加上相应的参数,但是别的函数就不一定能用此装饰器了
2.可以把*args和**kwargs作为装饰器内部函数的参数,表示可以接受任意数量和类型的参数
def my_decorator(func):
def wrapper(*args, **kwargs):
print('wrapper of decorator')
func(*args, **kwargs)
return wrapper
2.3 保留原函数
被装饰器装饰过的函数,其元信息会发生变化,可以调用函数名.__name__
进行查看元信息,通常可以使用内置装饰器@functools.wraps
将原函数的元信息拷贝到对应的装饰器函数里
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('wrapper of decorator')
func(*args, **kwargs)
return wrapper
@my_decorator
def greet(message):
print(message)
greet.__name__
输出:
'greet'
2.4 多个装饰器
@decorator1
@decorator2
@decorator3
def cunc():
...
其等效于@decorator1(@decorator2(@decorator3(func)))
,由里向外执行