装饰器详解

定义

1.装饰器:本质是函数。

2.功能:用来装饰其他函数,顾名思义就是,为其他的函数添加附件功能的。

原则

1.不能修改被装饰函数的源代码

2.不能修改被装饰函数的调用方式

装饰器知识储备

1.函数即变量

2.高阶函数

实现高阶函数有两个条件:

1)把一个函数名当做实参传给另外一个函数

2)返回值中包含函数名

3.嵌套函数

在一个函数的函数体内,用def 去声明一个函数,而不是去调用其他函数,称为嵌套函数。


def foo():
    
    print(" This is foo ")

    def bar():
 
        print(" This is bar")

    bar()
    

4.小成版装饰器


import time
def timer(func):
    def deco(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        stop_time = time.time()
        print("所用时间:%s" %(stop_time - start_time))
    return deco


@timer
def test1():
    time.sleep(3)
    print("this is test1")

test1()

5.最终版装饰器


import time
user,passwd = 'alex','abc123'
def auth(auth_type):
    print("auth func:",auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print("wrapper func args:", *args, **kwargs)
            if auth_type == "local":
                username = input("Username:").strip()
                password = input("Password:").strip()
                if user == username and passwd == password:
                    print("\033[32;1mUser has passed authentication\033[0m")
                    res = func(*args, **kwargs)  # from home
                    print("---after authenticaion ")
                    return res
                else:
                    exit("\033[31;1mInvalid username or password\033[0m")
            elif auth_type == "ldap":
                print("搞毛线ldap,不会。。。。")

        return wrapper
    return outer_wrapper

def index():
    print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
    print("welcome to home  page")
    return "from home"

@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs  page")

index()
print(home()) #wrapper()
bbs()



posted @ 2017-06-19 15:08  丶Shadows  阅读(70)  评论(0)    收藏  举报