首页 > 代码库 > python装饰器小例子

python装饰器小例子

import time

def timer(func): #timer(test1) func=test1
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(3)
print("in the test1")

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


test1()
test2("joan",5)


输出结果:

in the test1
the func run time 3.0043931007385254
in the test2 joan 5
the func run time 2.0034029483795166

python装饰器小例子