python 装饰器 part2

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了python 装饰器 part2脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

python 装饰器

传参

被装饰的函数带有参数的情况

接上一篇,直接上代码

import time
def decorator(func):
    def PRocess(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print('函数func(也就是被装饰的函数)的运行时间是:{}'.format(end-start))
    return process

@decorator # python 装饰器的正确使用,不需要传参
def decorated():
    time.sleep()
    print('decorated function')

@decorator # python 装饰器的正确使用,需要传参 
def decorated(key, val):
    time.sleep()
    print('decorated function')

# 此时不用再像上面一样赋值,可以直接调用
decorated()
decorated(key, val)

</python>

返回值

被装饰的函数有返回值在装饰器内部需return被装饰函数的调用

代码

import time
def decorator(func):
    def process(*args, **kwargs):
        start = time.time()
        return func(*args, **kwargs)
        # end = time.time()
        # print('函数func(也就是被装饰的函数)的运行时间是:{}'.format(end-start))
    return process

@decorator # python 装饰器的正确使用,不需要传参
def decorated():
    time.sleep()
    print('decorated function')
    return '来自不带参数的被装饰函数'

@decorator # python 装饰器的正确使用,需要传参 
def decorated(key, val):
    time.sleep()
    print('decorated function')
    return '来自带有参数的被装饰函数'

# 此时不用再像上面一样赋值,可以直接调用
decorated()
decorated(key, val)

装饰器带参数

@decorator(val='')

需要对装饰期代码再包装一层

代码

import time
def warpPEr(val_type):
    def decorator(func):
        def process(*args, **kwargs):
            start = time.time()
            return func(*args, **kwargs)
        return process
    return decorator

@decorator(val_type='') # python 装饰器的正确使用,不需要传参
def decorated():
    time.sleep()
    print('decorated function')
    return '来自不带参数的被装饰函数'

@decorator(val_type='') # python 装饰器的正确使用,需要传参 
def decorated(key, val):
    time.sleep()
    print('decorated function')
    return '来自带有参数的被装饰函数'

# 此时不用再像上面一样赋值,可以直接调用
decorated()
decorated(key, val)

脚本宝典总结

以上是脚本宝典为你收集整理的python 装饰器 part2全部内容,希望文章能够帮你解决python 装饰器 part2所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。