• wraps 在python 中作用


    简述:

      装饰器装饰一个函数时,函数本身就已经是一个新的函数;即函数名称或属性产生了变化。所以在python的functools模块中提供了wraps装饰函数来确保原函数在使用装饰器时不改变自身的函数名及应有属性。所以在装饰器的编写中建议加入wraps确保被装饰的函数不会因装饰器带来异常情况

    代码理解

    1.不加wraps装饰器

     1 # coding=utf-8
     2 from functools import wraps   
     3 def my_decorator(func):    
     4     def wrapper(*args, **kwargs):        
     5         '''decorator'''        
     6         print('Decorated function...')        
     7         return func(*args, **kwargs)    
     8     return wrapper   
     9 @my_decorator 
    10 def test():    
    11     """Testword"""     
    12     print('Test function')
    13 print(test.__name__, test.__doc__)
    14 
    15 打印结果:
    16 wrapper decorator

    2.加入wrapper函数后

     1 from functools import wraps   
     2 def my_decorator(func):    
     3     @wraps(func)    
     4     def wrapper(*args, **kwargs):        
     5         '''decorator'''        
     6         print('Decorated function...')        
     7         return func(*args, **kwargs)    
     8     return wrapper
     9 
    10 @my_decorator 
    11 def test():    
    12     """Testword"""     
    13     print('Test function')
    14 print(test.__name__, test.__doc__)
    15 
    16 打印结果:
    17 test Testword
  • 相关阅读:
    唐寅 《桃花庵歌》
    asp.net 后台隐藏div
    dataset的用法
    C#中的DateTime类型加减
    discuz! x2.5 文章添加分享按钮
    asp.net学习小网站
    table固定行和表头
    aspx.net开源的画图组件
    Global.asax详解
    int.Parse() int.TryParse
  • 原文地址:https://www.cnblogs.com/honglingjin/p/11675587.html
Copyright © 2020-2023  润新知