Python之裝飾器

Python 高階函數:

    1.把一個函數名作爲實參傳遞給另一個函數(在不修改被裝飾函數源代碼的情況下爲其添加功能)

    2.返回值中包含函數名(不修改函數的調用方式)

def test1():
    print("in the test1")

def test2(func): #接收函數名
    func()
    print("in the test2")
    return func  #返回函數內存地址

def test3():
    str = test2(test1)  #函數名test1 作爲實參傳遞給函數 test2,並接收test1的 內存地址賦值給str
    print(str)
    print("in the test3")
    
test3()


Python 嵌套函數:

    在函數當中再定義函數。

def test1():
    pirnt("in the test1")
    def test2(): 
        print("in the test2")


高階函數 +  嵌套函數 => 裝飾器

    裝飾器,在不修改源代碼的基礎上新增功能,並在不改變調用方式的前提下,實現功能添加,代碼實現如下:

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

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

@timer
def test2(name):
    time.sleep(1)
    print("name: ", name)

#test1 = timer(test1) #獲取的deco的內存地址,所以執行test1(),實際上就是執行deco()
test1()  #deco()

# @timer 分解步驟如下
test2 = timer(test2) # 把deco的內存地址給了test2,所以執行test2(),實際上就是執行deco()
print("test2: ", test2)
test2("lilei")  #deco("lilie")
import time

username = "alex"
password = "abc123"
def auth(mode):
    def out_wrapper(func):
        def wrapper(*args, **kwargs):
            if mode == "local":
                start_time = time.time()
                rec =func(*args, **kwargs)
                stop_time = time.time()
                print("the func run time is %s"% (stop_time-start_time))
                return rec
            elif mode == "ldap":
                print("in the ldap")
                start_time = time.time()
                rec = func(*args, **kwargs)
                stop_time = time.time()
                print("the func run time is %s" % (stop_time - start_time))
                return rec
        return wrapper
    return out_wrapper


def index():
    print("Welcome in the index page")

@auth(mode="local") #  home=wrapper()
def home(name):
    print("in the home", name)
    return "from home"

#@auth(mode="ldap")
def bbs():
    print("in the bbs")

index()
home("alex")

# @auth(mode="ldap") 分解步驟如下
#out_wrapper = auth(mode="ldap")  # 把 out_wrapper 內存地址給了 out_wrapper
# print("aa:", out_wrapper)
#bbs = out_wrapper(bbs)  # 把 wapper 的內存地址給了bbs,所以執行bbs(),實際上就是執行wapper(),
bbs = auth(mode="ldap")(bbs)  #兩步整合的結果: bbs = auth(mode="ldap")(bbs)
print("bbs:", bbs)
bbs()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章