#装饰器:本质是函数,功能:装饰其他函数,就是为他函数添加附加功能
#原则:1.不能修改被装饰的函数的源代码
# 2.不能修改被装饰函数的调用方式不能修改
#实现装饰器知识储备
#1.函数及“变量”
#2.高阶函数
#3.嵌套函数
#最终:高阶函数 + 嵌套函数 =》装饰器
import time
def timmer(func): #是一个函数 把test1的内存地址给了func
def warpper(*args,**kwargs):
start_time=time.time()
func() #这里就是执行test1
stop_time=time.time()
print("the func run time is %s" %(stop_time-start_time))
return warpper
@timmer #等于 test1=timer(test1)
def test1():
time.sleep(3)
print("in the test1")
#test1=timer(test1)
test1()
实例2:
import time
def timmer(func): #是一个函数
def warpper(*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 warpper
@timmer #test1=timer(test1)
def test1():
time.sleep(1)
print("in the test1")
@timmer #test1=timer(test1)
def test2(name):
print("name:",name)
test1()
test2("alex")
实例3:
import time
user,passwd = 'alex','abc123'
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("搞毛线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()) #wrapper()
bbs()