装饰器3(装饰函数带参数)

基础的装饰器:

#!/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()

 

posted @ 2017-10-01 18:49  幸福的好喜欢  阅读(120)  评论(0编辑  收藏  举报