装饰器:其本身为函数,用来装饰其他函数,也就是为其他函数增加功能。
装饰器设计遵循原则:1.不能修改被装饰函数的源代码
2.不能修改被装饰函数的调用方式
通常一个装饰器是由 高阶函数和嵌套函数组成。且会把函数当成变量使用。
装饰器1:被装饰函数有无参数通用版,装饰器本身无参数
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 #相当于test1=timer(test1) 则test1=deco
def test1():
time.sleep(1)
print('in the test1')
@timer
def test2(name,age):
print("test2:",name,age)
test1()
test2("hy",16)
装饰器2:装饰器本身带参数
import time
user,passwd="hy","123abc"
def auth (auth_type):
print("auth_type:",auth_type)
def deco(func):
def wrapper(*args,**kwargs):
username=input("Username:")
password=input("Password:")
if auth_type=="local":
if username==user and password==passwd:
print("\033[32;1m user has passed authentication\033[0m")
res=func(*args,**kwargs)
return res
else:
print("\033[31;1m Invalid username and password\033[0m")
elif auth_type=="ldap":
print("hehe")
return wrapper
return deco
def index():
print("Welcome to index paper")
@auth(auth_type="local")
def home():
print("Welcome to home paper")
return
@auth(auth_type="ldap")
def bbs():
print("Welcome to bbs paper")
index()
print(home())
bbs()
要明白其中功能用断点调试看。