7 Python学习记录—装饰器

python装饰器: 装饰器并不提供任何独特的功能,它所做的只是在函数定义语句上方,直接添加用来修改函数行为的装饰器函数。如果没有装饰器,也可以在定义函数之后,手动再封装一次该函数并重新赋值

@cache
def func():
    ...

类似于

def func():
    ...

func = cache(func)

7.1 基础知识

装饰器是通过包装目标函数来修改其行为的特殊高阶函数,绝大多数装饰器是利用函数的闭包实现的。 

定义timer无参数装饰器,记录方法运行时间

def timer(func):
    """打印耗时"""

    def decorated(*args, **kwargs):
        st = time.perf_counter()
        print('method run before')
        ret = func(*args, **kwargs)
        print('time cost: {} seconds'.format(time.perf_counter() - st))
        return ret

    return decorated


@timer
def test():
    print('test method running')


#运行test输出
method run before
test method running
time cost: 2.9311000000000614e-05 seconds

给装饰器增加参数,通过参数判断是否打印参数方法。

def timer(print_arg=False):
    """
    装饰器打印耗时
    :param print_arg: 是否打印默认是 False
    :return:
    """

    def decorator(func):
        """打印耗时"""

        def decorated(*args, **kwargs):
            st = time.perf_counter()
            print('method run before')
            ret = func(*args, **kwargs)
            if print_arg:
                print(f'{func.__name__}, args:{args}, kwargs:{kwargs}')
            print('time cost: {} seconds'.format(time.perf_counter() - st))
            return ret

        return decorated

    return decorator


@timer(print_arg=True)
def test(p1,p2,**kwargs):
    print('test method running')

##运行 test("name","age", **{"city":"wuhan"}) 输出
method run before
test method running
test, args:('name', 'age'), kwargs:{'city': 'wuhan'}
time cost: 4.03149999999991e-05 seconds

为了给装饰器增加参数,在原来的装饰器上又嵌套了一层。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值