Python 装饰器:
例子
import time
def timer(func):
def warpper(*args, **kwargs):
start_time = time.time()
func()
end_time = time.time()
print("this func cost time: %s" %(end_time - start_time))
return warpper
@timer
def test1():
time.sleep(3)
print("This is a test of decorator")
test1()
运行结果:
count = 49995000
func cost time : 0.0
49995000
func cost time : 0.0020055770874023438
由例子知, python装饰器 本质为函数
功能是为其它函数添加功能
那么装饰器, 什么才是装饰器呢
原则: 1.不能修改被装饰的函数的源代码
2.不能修改被装饰函数的调用方式
好, 那么装饰器由什么组成呢?
高阶函数 + 嵌套函数 =》 装饰器
如何理解高阶函数:
函数即变量。 由于函数可作为变量一样传入函数, 所以装饰器可将函数A传入新的函数B中返回得到函数A
的地址值而不改变函数A。
例:
import time
def gl():
time.sleep(1)
print('test zhe gl')
def test2(func):
print(func)
return func
gl=test2(gl)
gl() #run bar
嵌套函数:
例:
def foo():
print('in the foo')
def gl():
print('test gl')
gl()
foo()
所以, 装饰器由 高阶函数 + 嵌套函数 =》 装饰器
对于修饰带参数的函数
import time
def timer(func):
def warpper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print("this func cost time: %s" %(end_time - start_time))
return warpper
@timer
def test1(name):
time.sleep(3)
print("This is a test of decorator", name)
test1('测试')
对于有返回值的被修饰函数
import time
user, passwr = 'chenshouy', '123456'
def author(func):
def wrapper(*args, **kwargs):
username = input('Username:')
password = input('Password:')
if username == user and password == passwr:
print('welcome log in ')
rlt = func(*args, **kwargs)
return rlt
else:
exit("账号密码错误")
return wrapper
@author
def index():
print('this is a index')
return 'abc'
对于一个装饰器的多个引用
import time
user,passwd = 'chenshouy','123'
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("1")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
在auth传入参数时, 被修饰函数被传入时,自动传入到auth的下一层嵌套函数,即在使用多种调用时,需要多写一层外部函数