码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-10-01 19:28:07      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:log   local   参数   def   ...   /usr   strip   coding   war   

基础的装饰器:

#!/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(装饰函数带参数)

标签:log   local   参数   def   ...   /usr   strip   coding   war   

原文地址:http://www.cnblogs.com/sunweigogogo/p/7617595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!