Python中装饰器学习总结
本文研究的主要内容是Python中装饰器相关学习总结,具体如下。
装饰器(decorator)功能
- 引入日志
- 函数执行时间统计
- 执行函数前预备处理
- 执行函数后清理功能
- 权限校验等场景
- 缓存
装饰器示例
例1:无参数的函数
fromtimeimportctime,sleep
deftimefun(func):
defwrappedfunc():
print("%scalledat%s"%(func.__name__,ctime()))
func()
returnwrappedfunc
@timefun
deffoo():
print("Iamfoo")
foo()
sleep(2)
foo()
分析如下:
上面代码理解装饰器执行行为可理解成
foo=timefun(foo)
1,foo先作为参数赋值给func后,foo接收指向timefun返回的wrappedfunc
2,调用foo(),即等价调用wrappedfunc()
3,内部函数wrappedfunc被引用,所以外部函数的func变量(自由变量)并没有释放
4,func里保存的是原foo函数对象
例2:被装饰的函数有参数
fromtimeimportctime,sleep
deftimefun(func):
defwrappedfunc(a,b):
print("%scalledat%s"%(func.__name__,ctime()))
print(a,b)
func(a,b)
returnwrappedfunc
@timefun
deffoo(a,b):
print(a+b)
foo(3,5)
sleep(2)
foo(2,4)
例3:被装饰的函数有不定长参数
fromtimeimportctime,sleep
deftimefun(func):
defwrappedfunc(*args,**kwargs):
print("%scalledat%s"%(func.__name__,ctime()))
func(*args,**kwargs)
returnwrappedfunc
@timefun
deffoo(a,b,c):
print(a+b+c)
foo(3,5,7)
sleep(2)
foo(2,4,9)
例4:装饰器中的return
fromtimeimportctime,sleep
deftimefun(func):
defwrappedfunc():
print("%scalledat%s"%(func.__name__,ctime()))
func()
returnwrappedfunc
@timefun
deffoo():
print("Iamfoo")
@timefun
defgetInfo():
return'----hahah---'
foo()
sleep(2)
foo()
print(getInfo())
执行结果:
foocalledatSunJun1800:31:532017
Iamfoo
foocalledatSunJun1800:31:552017
Iamfoo
getInfocalledatSunJun1800:31:552017
None如果修改装饰器为returnfunc(),则运行结果:
foocalledatSunJun1800:34:122017
Iamfoo
foocalledatSunJun1800:34:142017
Iamfoo
getInfocalledatSunJun1800:34:142017
----hahah---
小结:一般情况下为了让装饰器更通用,可以有return
例5:装饰器带参数,在原有装饰器的基础上,设置外部变量
fromtimeimportctime,sleep
deftimefun_arg(pre="hello"):
deftimefun(func):
defwrappedfunc():
print("%scalledat%s%s"%(func.__name__,ctime(),pre))
returnfunc()
returnwrappedfunc
returntimefun
@timefun_arg("itcast")
deffoo():
print("Iamfoo")
@timefun_arg("python")
deftoo():
print("Iamtoo")
foo()
sleep(2)
foo()
too()
sleep(2)
too()
可以理解为
foo()==timefun_arg("itcast")(foo)()
例6:类装饰器
装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重写了call()方法,那么这个对象就是callable的。
classTest():
def__call__(self):
print('callme!')
t=Test()
t()#callme
类装饰器demo
classTest(object):
def__init__(self,func):
print("---初始化---")
print("funcnameis%s"%func.__name__)
self.__func=func
def__call__(self):
print("---装饰器中的功能---")
self.__func()
说明:
1.当用Test来装作装饰器对test函数进行装饰的时候,首先会创建Test的实例对象,并且会把test这个函数名当做参数传递到init方法中
即在init方法中的func变量指向了test函数体
2.test函数相当于指向了用Test创建出来的实例对象
3.当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的call方法
4.为了能够在call方法中调用原来test指向的函数体,所以在init方法中就需要一个实例属性来保存这个函数体的引用
所以才有了self.func=func这句代码,从而在调用__call方法中能够调用到test之前的函数体
@Test deftest(): print(“—-test—”) test() showpy()#如果把这句话注释,重新运行程序,依然会看到”–初始化–”
运行结果如下:
---初始化---
funcnameistest
---装饰器中的功能---
----test---
wraps函数
使用装饰器时,有一些细节需要被注意。例如,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)。
添加后由于函数名和函数的doc发生了改变,对测试结果有一些影响,例如:
defnote(func):
"notefunction"
defwrapper():
"wrapperfunction"
print('notesomething')
returnfunc()
returnwrapper
@note
deftest():
"testfunction"
print('Iamtest')
test()
print(test.__doc__)
运行结果
notesomething
Iamtest
wrapperfunction
所以,Python的functools包中提供了一个叫wraps的装饰器来消除这样的副作用。例如:
importfunctools
defnote(func):
"notefunction"
@functools.wraps(func)
defwrapper():
"wrapperfunction"
print('notesomething')
returnfunc()
returnwrapper
@note
deftest():
"testfunction"
print('Iamtest')
test()
print(test.__doc__)
运行结果
notesomething
Iamtest
testfunction
总结
以上就是本文关于Python中装饰器学习总结的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!