1. 程式人生 > >Python學習之路:裝飾器實現

Python學習之路:裝飾器實現

fun python run top 學習 pytho sleep light time()

import  time

def timer(func):#timer(test1) func=test1
    def deco():
        start_time=time.time()
        func()#run test1
        stop_time=time.time()
        print(‘the func run time is %s‘%(stop_time-start_time))
    return deco

def test1():
    time.sleep(3)
    print(‘in the test1‘)

def test2():
    time.sleep(3)
    print(‘in the test2‘)

print(timer(test1))
test1=timer(test1)
test1()#----->deco


#-------------------------------------------------------------------
import  time

def timer(func):#timer(test1) func=test1
    def deco():
        start_time=time.time()
        func()#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(3)
    print(‘in the test1‘)

@timer #加裝飾器
def test2():
    time.sleep(3)
    print(‘in the test2‘)

test1()
test2()

Python學習之路:裝飾器實現