Python3中装饰器的使用
较为复杂的装饰器使用:
user,passwd = 'hjc',111111 def auth(type): print('auth type:',type) def outwrapper(func): def wrapper(*args,**kwargs): if type == 'lll': username = input('username:').strip() password = int(input('password:').strip()) if user == username and passwd == password: print("\033[32;1muser pass ~~~~~~\033[0m") func(*args,**kwargs) else: exit("\033[31;1minvalid user ~~~~~~\033[0m") elif type == 'kkk': print('fuck off') return wrapper return outwrapper def index(): print("welcome to index page") @auth('lll') def home(): print("welcome to home page") @auth('kkk') def bbs(): print("welcome to bbs page") index() home() bbs()
输出结果如下:
auth type: lll
auth type: kkk
welcome to index page
username:hjc
password:111111
user pass ~~~~~~
welcome to home page
fuck off
2.较为简单的装饰器:
import time def timer(func): def inner(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print(stop_time-start_time) return inner @timer def wt(): print('hello wt!!!') wt()