装饰器181029
Posted l-dongf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器181029相关的知识,希望对你有一定的参考价值。
装饰器(语法糖decorator)定义
- 装饰器本质上是函数
- 装饰器的功能是为了装饰其他函数
为其他函数添加附加功能
装饰器特定的原则
- 不能修改被装饰函数的原代码
不能修改被装饰函数的调用方式
装饰器相关知识点
- 函数即“变量”
- 高阶函数
- 把一个函数名当做实参传给另外一个函数(在不修改函数的原代码为函数添加新功能)
- 返回值中包含函数名(不修改调用方式)
嵌套函数
高阶函数 + 嵌套函数 = 装饰器
高阶函数示例代码
# Author:Li Dongfei
import time
def bar():
time.sleep(3)
print("in the bar")
def test1(func):
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
test1(bar)
不修改调用方式代码示例
# Author:Li Dongfei
import time
def bar():
time.sleep(3)
print("in the bar")
def test2(func):
print(func)
return func
bar = test2(bar)
bar()
函数的嵌套
# Author:Li Dongfei
def foo():
print("in the foo")
def bar():
print("in the bar")
bar()
foo()
装饰器1
# Author:Li Dongfei
import time
def timer(func): #func == test1的内存地址
def deco():
start_time = time.time()
func() #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
return deco
def test1():
time.sleep(3)
print("in the test1")
def test2():
time.sleep(3)
print("in the test2")
test1 = timer(test1)
test1()
装饰器2
# Author:Li Dongfei
import time
def timer(func): #func == test1的内存地址
def deco():
start_time = time.time()
func() #run test1()
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
return deco
@timer # test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer
def test2():
time.sleep(3)
print("in the test2")
test1()
test2()
带参数传递的装饰器
# Author:Li Dongfei
import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is %s" %(stop_time - start_time))
return deco
@timer
def test1():
time.sleep(1)
print("in the test1")
@timer #test2 = timer(test2) = deco , test2(name) == deco(name)
def test2(name):
time.sleep(2)
print("test2:",name)
test1()
test2("dongfei")
装饰器示例:实现验证功能
# Author:Li Dongfei
import time
user,passwd = 'dongfei','123456'
def auth(auth_type):
def outer_wrapper(func):
def wrapper(*args,**kwargs):
username = input("Username: ").strip()
password = input("Password: ").strip()
if auth_type == "local":
if user == username and passwd == password:
print("login successful")
res = func(*args,**kwargs)
return res #返回被装饰函数的执行结果
else:
exit("login failure")
elif auth_type == "ldap":
print("ldap认证")
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")
index()
print(home())
bbs()
以上是关于装饰器181029的主要内容,如果未能解决你的问题,请参考以下文章