Python闭包和装饰器用法实例详解
本文实例讲述了Python闭包和装饰器用法。分享给大家供大家参考,具体如下:
Python的装饰器的英文名叫Decorator,作用是完成对一些模块的修饰。所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去。
闭包
1.函数引用
#coding=utf-8
deftest1():
print('Thisistest1!')
#调用函数
test1()
#引用函数
ret=test1
#打印id
print('test1\t的地址:',id(test1))
print('ret\t\t的地址:',id(ret))
print('你会发现test1的地址和ret的地址是一样的!')
#通过引用调用函数
ret()
运行结果:
Thisistest1!
test1 的地址:139879303947128
ret 的地址:139879303947128
你会发现test1的地址和ret的地址是一样的!
Thisistest1!
1.什么是闭包
在嵌套函数中,内部函数用到了外部函数的变量,则
称内部函数为闭包。
python中的闭包从表现形式上定义(解释)为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure).
上代码:
#coding=utf-8
defouter(num):
definner(num_in):
returnnum+num_in
returninner
#10赋值给了num
ret=outer(10)
#20赋值给了num_in
print('ret(20)=',ret(20))
#30赋值给了num_in
print('ret(30)=',ret(30))
运行结果:
ret(20)= 30
ret(30)= 40
闭包的应用例子一:
看代码:
#coding=utf-8 defline_conf(a,b): defline(x): returna*x+b returnline line1=line_conf(1,1) line2=line_conf(4,5) print(line1(5)) print(line2(5))
运行结果:
6
25
这个例子中,函数line与变量a,b构成闭包。在创建闭包的时候,我们通过line_conf的参数a,b说明了这两个变量的取值,这样,我们就确定了函数的最终形式(y=x+1和y=4x+5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。
如果没有闭包,我们需要每次创建直线函数的时候同时说明a,b,x。这样,我们就需要更多的参数传递,也减少了代码的可移植性。
闭包思考:
1.闭包似优化了变量,原来需要类对象完成的工作,闭包也可以完成。
2.由于闭包引用了外部函数的局部变量,则外部函数的局部变量没有及时释放,消耗内存。
代码如下:
#coding=utf-8 #定义函数:完成包裹数据 defmakeBold(func): defwrapped(): return""+func()+"" returnwrapped #定义函数:完成包裹数据 defmakeItalic(fn): defwrapped(): return""+fn()+"" returnwrapped @makeBold deftest1(): return"helloworld-1" @makeItalic deftest2(): return"helloworld-2" @makeBold @makeItalic deftest3(): return"helloworld-3" print(test1()) print(test2()) print(test3())
运行结果:
helloworld-1
helloworld-2
helloworld-3
装饰器(decorator)功能
1.引入日志
2.函数执行时间统计
3.执行函数前预备处理
4.执行函数后清理功能
5.权限校验等场景
6.缓存
装饰器示例
例1:无参数的函数
代码如下:
#coding=utf-8
fromtimeimportctime,sleep
deftime_func(func):
defwrapped_func():
print('%scallat%s'%(func.__name__,ctime()))
func()
returnwrapped_func
@time_func
deffoo():
print('iamfoo!')
foo()
sleep(2)
foo()
运行结果:
foocallatThuAug2421:32:392017
iamfoo!
foocallatThuAug2421:32:412017
iamfoo!
例2:被装饰的函数有参数
#coding=utf-8
fromtimeimportctime,sleep
deftimefunc(func):
defwrappedfunc(a,b):
print('%scalledat%s'%(func.__name__,ctime()))
print(a,b)
func(a,b)
returnwrappedfunc
@timefunc
deffoo(a,b):
print(a+b)
foo(3,5)
sleep(2)
foo(2,4)
运行结果:
foocalledatThuAug2421:40:202017
35
8
foocalledatThuAug2421:40:222017
24
6
例3:被装饰的函数有不定长参数
#coding=utf-8
fromtimeimportctime,sleep
deftimefunc(func):
defwrappedfunc(*args,**kwargs):
print('%scalledat%s'%(func.__name__,ctime()))
func(*args,**kwargs)
returnwrappedfunc
@timefunc
deffoo(a,b,c):
print(a+b+c)
foo(3,5,7)
sleep(2)
foo(2,4,9)
运行结果:
foocalledatThuAug2421:45:132017
15
foocalledatThuAug2421:45:152017
15
例4:装饰器中的return
如下:
#coding=utf-8
fromtimeimportctime
deftimefunc(func):
defwrappedfunc():
print('%scalledat%s'%(func.__name__,ctime()))
func()
returnwrappedfunc
@timefunc
defgetInfo():
return'---hello---'
info=getInfo()
print(info)
代码如下:
getInfocalledatThuAug2421:59:262017
None
如果修改装饰器为returnfunc():
如下:
#coding=utf-8
fromtimeimportctime
deftimefunc(func):
defwrappedfunc():
print('%scalledat%s'%(func.__name__,ctime()))
returnfunc()
returnwrappedfunc
@timefunc
defgetInfo():
return'---hello---'
info=getInfo()
print(info)
代码如下:
getInfocalledatThuAug2422:07:122017
---hello---
总结:
一般情况下为了让装饰器更通用,可以有return
例5:装饰器带参数,在原有装饰器的基础上,设置外部变量
#coding=utf-8
fromtimeimportctime,sleep
deftimefun_arg(pre="hello"):
deftimefunc(func):
defwrappedfunc():
print('%scalledat%s'%(func.__name__,ctime()))
returnfunc()
returnwrappedfunc
returntimefunc
@timefun_arg('hello')
deffoo1():
print('iamfoo')
@timefun_arg('world')
deffoo2():
print('iamfoo')
foo1()
sleep(2)
foo1()
foo2()
sleep(2)
foo2()
运行结果:
foo1calledatThuAug2422:17:582017
iamfoo
foo1calledatThuAug2422:18:002017
iamfoo
foo2calledatThuAug2422:18:002017
iamfoo
foo2calledatThuAug2422:18:022017
iamfoo
可以理解为:
foo1()==timefun_arg("hello")(foo1())
foo2()==timefun_arg("world")(foo2())
例6:类装饰器
装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重载了call()方法,那么这个对象就是
callable的。
classTest():
def__call__(self):
print('callme!')
t=Test()
t()#callme
类装饰器demo:
classDecofunc(object):
def__init__(self,func):
print("--初始化--")
self._func=func
def__call__(self):
print('--装饰器中的功能--')
self._func()
@Decofunc
defshowpy():
print('showpy')
showpy()#如果把这句话注释,重新运行程序,依然会看到"--初始化--"
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。