装饰器

#装饰器本质是函数,用来装饰其他函数,也就是为其他函数添加附加功能

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

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

3)高阶函数+嵌套函数 =》装饰器

 

#高阶函数在定义

1)把一个函数名当作实参传给另外一个函数(不修改被装饰函数源代码的情况下为其添加功能)

2)返回值中包括函数名(不修改函数的调用方式)

 

#高阶函数+嵌套函数 =》装饰器
def timmer(func):  #将函数作为参数被调用
    def warpper(*args,**kwargs):
        start_time= time.time()
        func()  ###该步骤调用test1()
        stop_time = time.time()
        print('the function run time is %s'%(stop_time-start_time))
    return warpper

@timmer  # 也等同于test1 = timmer(test1)
def test1():
    time.sleep(0.21)
    print("It's test1")

test1()   #函数调用装饰器
decerator

 

函数嵌套

在一个函数体内用def去申明一个新函数,而不是去调用。

print("\n利用嵌套函数写装饰器\n")
def timer(func): #time(test1) func = test1
    def deco(*args,**kargs):   #装饰器定义非固定参数
        start_time = time.time()
        func(*args,**kargs) #run test1
        stop_time = time.time()
        print("The function run time is %s"%(start_time - stop_time))
    return deco

@timer # test1 = timer(test1) #test1传给timer中的func
def test1():
    time.sleep(1)
    print("in the function test1")

#test1 = timer(test1) #指针
test1()

@timer
def test2(name,age):
    time.sleep(1)
    print("in the function test2!!",name,age)

#test2 = timer(test2) #指针
test2("yyw",22)
利用嵌套函数写装饰器
###利用嵌套函数写装饰器
import time
user,pwd = "yyw","123"
def auth(auth_type):
    print("auth type",auth_type)
    def outer_wrapper(func):
        print("outter wrpper")  #print("outter wrpper", func)出错
        def wrapper(*args,**kargs):
            print("outter wrpper", *args, **kargs)
            if auth_type == "local":
                _user = input("Username>>>:").strip()
                _pwd  = input("Password>>>").strip()
                if user ==_user and pwd ==_pwd:
                    print("\033[32;1mUser has passed Authentication\033[0m")
                    #res = func(*args, **kargs) #from home
                    print("--- after authentication ---")
                   # return res
                else:
                    exit("\033[31;1mUser has passed Authentication\033[0m")
            elif auth_type =="ldap":
                print("ldap 认证还没有开放")
        return wrapper
    return outer_wrapper

def index():
    print("welcome to zenhr!")

@auth(auth_type="local") #home= wrapper()
def home():
    print("Welcome to Zenhr Home!")
    return("from Home")

@auth(auth_type="ldap")
def bbs(A):
    print("Welcome to BBS!")
    return("from BBS")

#index()
home()
bbs("bbs")
条件嵌套调用装饰器案例

 

posted @ 2018-05-06 17:46  ywyin  阅读(155)  评论(0编辑  收藏  举报