1. 程式人生 > >裝飾器3(裝飾函數帶參數)

裝飾器3(裝飾函數帶參數)

odi sleep user strip() app time logs sun password

基礎的裝飾器:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
username,password = "sunwei","123"

def auth(func):
    def wrapper():
        user = input("please input your name:").strip()
        passwd = input("please input your password:").strip()
        if user == username and passwd == password:
            
print("\033[32;40m驗證通過\033[0m") func() else: print("\033[31;40m驗證失敗\033[0m") return wrapper @auth def test1(): print("welcome to test1...") @auth def test2(): print("welcome to test2...") test1() test2()

升級一下,裝飾器函數帶參數....

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time username,password = "sunwei","123" def auth(auth_type): def out_wrapper(func): def wrapper(*args,**kwargs): if auth_type == "local": user = input("please input your name:").strip() passwd = input("please input your password:").strip()
if user == username and passwd == password: print("\033[32;40m驗證通過\033[0m") func(*args,**kwargs) else: print("\033[31;40m驗證失敗\033[0m") else: time.sleep(3) exit("我不知道什麽是ldap...") return wrapper return out_wrapper @auth(auth_type = "local") #test1 = auth(test1) def test1(): print("welcome to test1...") @auth(auth_type = "ldap") def test2(): print("welcome to test2...") test1() test2()

裝飾器3(裝飾函數帶參數)