python中wraps作用

functools.wraps 的作用是将原函数对象的指定属性复制给包装函数对象, 默认有 modulenamedoc,或者通过参数选择。

import functools

def itcast1(fun):

    # 带参数的装饰器

    #wraps是用来将inner函数的属性设置为fun的属性值

   @functools.wraps(fun)

    def inner(*args, **kwargs):

        print("itcast1 start")

        fun(*args, **kwargs)

        print("itcast1 end")

    return inner

上述代码可表示为:

# def itcast1(fun):

#     def inner(*args, **kwargs):

#        print("itcast1 start")

#        fun(*args, **kwargs)

#        print("itcast1 end")

#    inner.__name__ = fun.__name__

#    inner.__doc__ = fun.__doc__

#     return inner
>>> @itcast1
... def say_hello():
...     print('say_hello')
... 
>>> print(say_hello.__name__)
say_hello

若itcast1中没有使用wraps:

>>> def itcast1(fun):
...     def inner(*args, **kwargs):
...             print('itcast1 start')
...             fun(*args, **kwargs)
...             print("itcast1 end")
...     return inner
... 
>>> @itcast1
... def say_hello():
...     print('say_hello')
... 
>>> print(say_hello.__name__)
inner
>>> say_hello()
itcast1 start
say_hello
itcast1 end

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值