python学习笔记之基础操作(七)函数闭包和装饰器

版权声明:所有资料资源均应用作教育用途,请勿用作商业用途 https://blog.csdn.net/qq_38876114/article/details/83752067

装饰器

为其它函数添加附加功能,
原则:不修改装饰的函数源代码和调用方式
装饰器=高阶函数+函数嵌套+闭包 

高阶函数

函数的参数或者返回值是一个函数
#没有改变函数体,但是改变了调用方式
def test(func):
	print(fun)
	func()
def foo():
	print("saaa")
test(foo)  
#没有改变调用方式   
def test2(func):
	return func
foo = test2(foo)
foo()   

函数嵌套

函数内部定义新的函数,需要注意局部变量和全局变量的问题,在嵌套的结构中,变量的搜索优先在当前作用域内找,如果没有,则向上一级寻找,由于python没有像java那样区分定义和赋值的概念,因此在内层和外层同时读一个变量进行赋值操作只会在内层生效,外层不会生效,好像第二个例子
def father():
	print("father")
	def son():
		print("son")
	son()
	print(locals())#打印当前层局部变量
father()
def f():
	x = 1
	def r():
		x = 2
		print(x)
	r()
	print(x)
输出:	
2
1
会将内层定义的变量和外层区分开

装饰器框架

# @timmer 相当于test=timmer(test)
def timmer(func):
	def wrapper(*args,**kwargs):
		print(func)
		res = func(*args,**kwargs)
		return res    #注意需要有这个返回值,否则无法实现有返回值的装饰
	return wrapper
例如,有如下函数,想要新增打印函数地址的功能
,即上述装饰器
def test():
	print("1")
res = timmer(test)    #获得了新的wrapper的函数地址
res()   #执行wrapper

猜你喜欢

转载自blog.csdn.net/qq_38876114/article/details/83752067