python--装饰器
装饰器:高阶函数 + 嵌套函数 = 装饰器
定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能
原则:不能修改被装饰函数的源代码;
不能修改被装饰的函数的调用方式;
实现装饰器知识储备:
- 函数即“变量”
- 高阶函数(把一个函数名,当做实参传给另一个函数; 2,返回值中包含函数名)
- 嵌套函数
没有参数的小小装饰器:
import time
def timer(func): #func函数名,就是函数func()的内存地址
def deco():
start_time = time.time()
func()
stop_time = time.time()
print('运行时间是:%s'%(stop_time-start_time))
return deco #此时的deco就是函数deco() 在内存中的位置
def free():
time.sleep(3)
print('in the freee')
@timer #bbs = timer(bbs)
def bbs():
time.sleep(2)
print('\033[31min the bbsssssss\033[0m')
free()
bbs()
传参数的 中级装饰器:
def timer(func): #func函数名,就是函数func()的内存地址
def deco(*args,**kwargs): #************传参数,func需要传参数
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print('运行时间是:%s'%(stop_time-start_time))
return deco #此时的deco就是函数deco() 在内存中的位置
据说这是终极版,来装隔壁:
# -*- coding: utf-8 -*-
username,password = 'alex','asdf'
def auth(type):
def out_wraper(func):
def decor():
if type == 'local':
user_input = input('username: ').strip()
passwd_input = input('password: ').strip()
if user_input == username and passwd_input == password:
print('welcome, you got current passwd !!!\033[34m current username\033[0m')
func()
else:
exit('ooooh, shit , wrong password')
elif type =='ldap':
print('还没有学会ldap,ldap \033[36m ldapdddp\033[0m')
pass
return decor
return out_wraper
def free():
print('\033[31mNum1:this is freeeeeeeeeee\033[0m')
@auth(type = 'ldap')
def home():
print('\033[32mNum2:welcome to your home,,,,home\033[0m')
@auth(type = 'local')
def bbs():
print('\033[33mNum3:这里是bbs bbs bbs bbsbbssssss\033[0m')
free()
home()
bbs()
自古深情留不住,总是套路得人心!
感觉学习也是,多多见识,多多套用!

浙公网安备 33010602011771号