1. 程式人生 > >day20函式的裝飾器和閉包

day20函式的裝飾器和閉包

---------------------函式的巢狀------
    l=[1,2]
    l.__iter__()#iter(l)
    裝飾器:本質就是函式的修飾作用
    原則:
    1.不修改被修飾函式的原始碼
    2.不修改被修飾函式的呼叫方式

    import time
    l=[1,3]
    def cal(l):
        res=0
        start_time=time.time()
        for i in l:
            time.sleep(0.1)
            res+=i
        stop_time=time.time()
        print('函式的執行時間是:%s'%(stop_time-start_time))
        return res
    start=cal(l)

    裝飾器=高階函式+函式巢狀+閉包
    高階函式:
    1.函式的接受引數是一個函式名稱
    2.函式的返回值是一個函式名稱
    3.滿足上面一個函式就是高階函式
    import time
    def foo():
        print('你好啊')
        time.sleep(2)
    def test(func):
        print(func)
        start_time=time.time()
        func()
        stop_time=time.time()
        print('函式的執行時間:%s'%(stop_time-start_time))
    test(foo)


    def foo():
        print('from foo')
    def test():
        func=foo()
        return func
    foo=test()

    多執行一次
    #高階函式
    def foo():
        time.sleep(3)
        print('來之foo')
    def timer(func):
        start_time=time.time()
        func()
        stop_time=time.time()
        print('函式的執行時間是:%s'%(stop_time-start_time))
        return func
    foo=timer(foo)
    foo()

    函式巢狀
    def father(name):
        print('from father %s'%name)
        def soon():
            print('from soon')
        print(locals())
    father('alex')
    #閉包其實就是巢狀來執行
    import time
    @timmer
    def timmer(func):
        def wrapper():
            start_time=time.time()
            print(func)
            func()
            stop_time=time.time()
            print("函式的執行時間是:%s"%(stop_time-start_time))
        return wrapper
    def test():
        time.sleep(2)
        print("test函式執行完畢")
    #test=timer(test)
    test()
    #@符號就是語法糖


    import time
    def timmer(func): #func=test
        def wrapper():
            # print(func)
            start_time=time.time()
            res=func() #就是在執行test()
            stop_time = time.time()
            print('執行時間是%s' %(stop_time-start_time))
            return res
        return wrapper

    @timmer #test=timmer(test)
    def test():
        time.sleep(3)
        print('test函式執行完畢')
    res=test()
    print(res)
-------------裝飾器例項--------------
    import time
    def timmer(func):
        def wapper(*args,**kwargs):
            start_time=time.time()
            stop_time=time.time()
            res=func(*args,**kwargs)
            print('函式的執行時間是:%s'%(stop_time-start_time))
            return res
        return wapper()


    @timmer
    def cal(l):
        res=0
        for i in l:
            time.sleep(0.1)
            res+=i
        return res
    res=cal(range(10))
    print(res)
==================加上返回值裝飾器==========
    import time
    def timmer(func): #func=test
        def wrapper():
            # print(func)
            start_time=time.time()
            res=func() #就是在執行test()
            stop_time = time.time()
            print('執行時間是%s' %(stop_time-start_time))
            return res
        return wrapper

    @timmer #test=timmer(test)
    def test():
        time.sleep(3)
        print('test函式執行完畢')
    res=test()
    print(res)
====================加上引數裝飾器=========
    import time
    def timmer(func): #func=test
        def wrapper(*args,**kwargs):
            # print(func)
            start_time=time.time()
            res=func(*args,*kwargs) #就是在執行test()
            stop_time = time.time()
            print('執行時間是%s' %(stop_time-start_time))
            return res
        return wrapper

    @timmer #test=timmer(test)
    def test(name,age):
        time.sleep(3)
        print('test的函式執行完畢,名字是【%s】,年齡是【%s】'%(name,age))
        print('test函式執行完畢')
        return '這是test的返回值'
    @timmer
    def test1(name,age,gende):
        time.sleep(2)
        print('test1的函式執行完畢,名字是【%s】,年齡是【%s】,性別是:【%s】'%(name,age,gende))
        print('test1函式執行完畢')
        return '這是test1的返回值'

    res=test('lignhaifeng',18)
    res1=test1('ouyang','18','boy')
    print(res)
    print(res1)

    解壓序列進行取包
    sl=[1,2,3,4,54,66,76,8768,89786,989,906,90,90987,988,9889]
    a,b,c,*_,d=sl#中間不需要的值用*_代替
    print(a,b,c,d)
    a=1
    b=2
    a,b=b,a
    print(a,b)

=====================裝飾器驗證===================
    import os
    user_dic={'username':None,'login':False}
    user_list=[
        {'name':'alex','passwd':'123'},
        {'name':'linhaifeng','passwd':'123'},
        {'name':'wupeiqi','passwd':'123'},
        {'name':'yuanhao','passwd':'123'},
    ]
    current_dic={'username':None,'login':False}
    def auth(auth_type='filedb'):
        def auth_func(func):
            def wrapper(*args,**kwargs):
                print("認證的型別是",auth_type)
                if auth_type=='filedb':
                    if current_dic['username'] and current_dic['login']:
                        res = func(*args, **kwargs)
                        return res
                    username=input('使用者名稱:').strip()
                    passwd=input('密碼:').strip()
                    for user_dic in user_list:
                        if username == user_dic['name'] and passwd == user_dic['passwd']:
                            current_dic['username']=username
                            current_dic['login']=True
                            res = func(*args, **kwargs)
                            return res
                    else:
                        print('使用者名稱或者密碼錯誤')
                elif auth_type=='ldap':
                    print('鬼才會玩這個')
            return wrapper

        return auth_func
    @auth(auth_type='filedb')
    def index():
        print('歡迎來到京東主頁')

    @auth(auth_type='filedb')
    def home(name):
        print('歡迎回家%s' %name)

    @auth(auth_type='filedb')
    def shopping_car(name):
        print('%s的購物車裡有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))

    print('before-->',current_dic)
    index()
    print('after--->',current_dic)
    home('產品經理')
    #shopping_car('產品經理')