装饰器

所谓装饰器其实就是高阶函数函数嵌套结合起来的高级应用。装饰器的功能:简单来说,就是在不改变函数的调用方式的情况下为函数增加某一个特定的功能。
高阶函数:把函数当作参数传入。
函数嵌套:在函数里面用def字段定义一个函数。

例子1:

如下面的例子所示,添加一个@timer装饰器,为test1和test2函数增加一个计算函数执行时间的功能,而且不改变这两个函数的调用方式。

__author__ = '__yuanlei__'

import time
def timer(func):   # timer(test1)   func = test1 
    def deco(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)   #run test1()
        stop_time = time.time()
        print("the func run time is %s"%(stop_time-start_time))
    return deco

@timer  #test1 = timer(test1)
def test1():
    time.sleep(1)
    print("in the test1")

@timer  #test2 = timer(test2)
def test2(name, age):
    time.sleep(:)
    print("test:",name,age)

test1()
test2("yl",25)

# 输出
# in the test1
# the func run time is 1.0
# ('test2:', 'yl', 25)
# the func run time is 2.00100016594

例子2:使得装饰器可以出入函数

__author__ = '__yuanlei__'

import time
user, passwd = 'yl','1993'
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)
                    print("--after authentication")
                    return res
                else:
                    exit("\033[32;1mInvalid username or password\033[0m")
            elif auth_type == 'ldap':
                print('ldap,do not understand......')
        return wrapper
    return outer_wrapper

def index():
    print("welcome to index page")

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

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

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


# 输出:
# auth func: local
# auth func: ldap
# welcome to index page
# wrapper func args:
# Username:yl
# Password:1993
# User has passed authentication
# welcome to home page
# --after authentication
# from home
# wrapper func args:
# ldap,do not understand......