python 裝飾器從放棄到玩轉(中級)

前面咱們說到裝飾器的初步使用ide

需求一:
函數

那我如今有個需求,原函數是這樣的內存

def test1():ci

    a = "test1"
it

    time.sleep(3)class

    return  atest

能夠看到是有返回值的,可咱們以前的裝飾器,並無處理原函數的返回值的邏輯,那麼我如今怎麼辦,看代碼im


def record_time(func):裝飾器

    def warpper():dict

        start_time = time.time()

        a = func()

        end_time = time.time()

        print "總共用時:" + str(int(end_time) - int(start_time))

        return a

    return warpper


@record_time

def test1():

    a = "test1"

    time.sleep(3)

    return a


r = test1()

print r


步驟解釋:

  1. @record_time== test1=record_time(test1)=warpper

  2. r = test1()

    test1() == warpper()

    裏面直接return了原test1函數的返回值

  3. r = 原test1的返回值


需求一:

def test1(name):

    a = name

    time.sleep(3)

    return  a


def test2(name,age):

    a = name

    b = age

    dict = {}

    dict["name"] = a

    dict["age"] = age

    time.sleep(3)

    return  dict

我如今的函數須要傳值,而且每一個函數可能傳的參數不是固定的,要求記錄函數的執行時間


請看實現的代碼以下

def record_time(func):

    def warpper(*args,**kwargs):

        start_time = time.time()

        a = func()

        end_time = time.time()

        return a

    return warpper 


@record_time

def test1(name):

    a = name

    time.sleep(3)

    return  a


@record_time

def test2(name=name ,age=age):

    a = name

    b = age

    dict = {}

    dict["name"] = a

    dict["age"] = age

    time.sleep(3)

    return  dict


r = test1("test01")

r1 = test2("test02",20)

print r,r1

解釋:

  1. @record_time == test1 = record_time(test1) = warpper(前面忘講了,這個就是warpper的內存地址)

  2. @record_time == test2 = record_time(test2) = warpper

  3. test1("test01")== warpper("test01"),而warpper函數能夠容許你傳入不固定參數*agrs(元祖)和關鍵字參數(**kwargs)

  4. warpper中執行了原來的test01和test02

  5. 返回各自的結果

相關文章
相關標籤/搜索