python装饰器
装饰器器的出现主要是为了在不修改原函数的前提下对被装饰函数添加一些额外功能(如打印日志,权限验证等),利用的python原理,就是一切兼对象,函数也可以作为参数进行传递。
#!/usr/bin/env python
import time
def demo(myfunc):
def wraper():
print("startT:",time.time())
myfunc()
print("endT:",time.time())
return wraper #demo()被调用后,运行此函数返回wraper()函数的引用wraper
@demo # 此行代码等同于,myfunc=demo(myfunc)=wraper
def myfunc():
print("hello world")
myfunc() #此时myfunc()=wraper()
print("############## 带参数函数 #####################")
def decorator(myfunc):
def wraper(*args,**kwargs):
print("beginning ...........!")
print("args is ",args,kwargs)
a = myfunc(*args,**kwargs)
print("end ..............!")
return a
return wraper #decorator()被调用后,运行此函数返回wraper()函数的引用wraper
@decorator ## 此行代码等同于,myfunc=decorator(myfunc)=wraper
def func(n1,n2):
print("this is func self")
print("func self n1 + n2 is :",n1+n2)
return n1+n2
print(func(3,4)) #此时func(3,4)=wraper(3,4)
#结果:
startT: 1580032988.7694573
hello world
endT: 1580032988.7694573
############## 带参数函数 #####################
beginning ...........!
args is (3, 4) {}
this is func self
func self n1 + n2 is : 7
end ..............!
7

浙公网安备 33010602011771号