python 装饰器
##装饰器的定义 :
## 1、装饰器的本质是函数, (装饰其他函数)就是为其他函数添加附加的功能
## 原则 : 1、不能修改被装饰的函数的源代码
# 2、不能修改被装饰的函数的调用方式
## a、 把一个函数名的当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
##b、返回值中包含函数名(不能修改函数的调用方式)
## 装饰器前奏 : 实现了 a 中的功能
def bar():
time.sleep(3)
print('in the bar')
def test1(func):
start_time = time.time()
func()
stop_time = time.time()
test1(bar)
# 函数的嵌套 实现了新的功能,但是也改变了相应的代码
def foo():
print('in the foo')
def bar():
print('in the bar')
bar()
foo()
# the first code
import time
def timmer(func):
def warpper(*args,**kwargs):
start_time = time.time()
func()
stop_time = time.time()
print('the func run time is %s'%(stop_time-start_time))
return warpper
@timmer # 语法糖 相当于test1 = timmer (test1)
# 由于是嵌套函数,所以 其实相当于执行了warpper()函数,wapper函数里面有func()
def test1():
time.sleep(3)
print('in test1')
test1()
# 执行结果 in test1
#the func run time is 3.00099778175354
#the second code
# 由于@timer == test1 = timer(test1) 也就是说 其实deco函数就相当与test1函数,所以需要传递参数的话,只需要在deco()中加入参数变量就可以了
import time
def timer(fun):
def deco (*args,**kwargs):
start_time = time.time()
fun(*args,**kwargs)
end_time= time.time()
print('the func run time is %s'%(end_time - start_time))
return deco
@timer #test1 = timer (test1)
def test1 ():
time.sleep(3)
print('in the test1')
@timer #test2 = timer (test2)
def test2(name ,age):
time.sleep(3)
print ('in the test2', name ,age)
test1()
test2('dh','25')
#执行结果:
#in the test1
#the func run time is 3.000493049621582
#in the test2 dh 25
#the func run time is 3.000492572784424
# the third code
#
user = 'dh'
passwd = '123456'
def auth(auth_type):
print('auth_type:',auth_type)
def out_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type == 'local':
usrname = input('username:').strip()
password = input('password').strip()
if user == usrname and passwd == password:
print ('1muser has passed authentication ')
res =func(*args,**kwargs)
return res
else:
exit('1mInavlid username or password')
elif auth_type == 'ldap':
print ('ladp 不可以使用')
return wrapper
return out_wrapper
def index():
print ('welcom to index page')
@auth(auth_type = 'local') # home = auth (auth_type)
def home():
print('welcom to home page')
return 'from home'
@auth(auth_type = 'ldap') # bbs = auth(auth_type,bbs()) # 传递了两个参数 必定是把两个参数分别给了两个函数,两个函数然分别接收两个参数
def bbs(): # 也就是说 其实最后bbs依然是接收了wrapper的地址
# 之所以定义三层,是因为需要两个参数的传递,第一层传入一个键值参数,第二个传入了一个函数 并且第二层的函数是直接执行的 第三层函数相当于直接返回是地址
# 把地址返回给了bbs bbs() 相当于 直接执行wrapper(*args,**kwargs)
print('welcom to bbs page')
index()
print(home())
bbs()
浙公网安备 33010602011771号