首页 > 其他 > 详细

20210112-1 装饰器之案例剖析2

时间:2021-01-12 16:29:38      阅读:27      评论:0      收藏:0      [点我收藏+]
1-1
# 如果 test2 里面有一个参数
import time
def timer(func):    
    def deco():
        start_time = time.time()
        func()      
        stop_time = time.time()
        print("the func run time  is %s" %(stop_time-start_time))    
    return deco     

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

@timer
def test2(name):
    print("test2:",name)

test1() 
test2()
--->
TypeError: test2() missing 1 required positional argument: name
# 结果是出错的,test2 缺少位置参数 name
# @timer 相当于 test2 = timer(test2) 
# test2 传到里面都做了什么? test2 → func → 执行 deco 所以,内嵌的deco函数,执行了吗?
# return deco,直接返回了 deco 的内存地址
# test2 其实是等于 deco,于是 test2()相当于 deco(),执行到 func()时,相当于执行到了 test2()
# 但是 test2 是要求传参数的,test2()没有传参;所以会报错
# 那么,这种情况应该如何处理?如何把参数传进来?
1-2
# test2(name),其实就是相当于 deco(name)
import time
def timer(func):    
    def deco(arg1):
        start_time = time.time()
        func(arg1)      
        stop_time = time.time()
        print("the func run time  is %s" %(stop_time-start_time))    
    return deco     

@timer
def test2(name):
    print("test2:",name)

test2("alex")
--->
test2: alex
the func run time  is 0.0
1-2-1
# 如果传入两个参数呢?
# 要装饰的函数可能是各种各样的功能
# 所以需要 *args  **kwargs
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  is %s" %(stop_time-start_time))    
    return deco     

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

@timer
def test2(name,age):
    print("test2:",name,age)

test1()
test2("alex",11)
--->
in the test1
the func run time  is 3.0008721351623535
test2: alex 11
the func run time  is 0.0009975433349609375

 

20210112-1 装饰器之案例剖析2

原文:https://www.cnblogs.com/azxsdcv/p/14265750.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!