python装饰器学习的时候有两点需要注意一下

1,被装饰器装饰的函数取其func.__name__和func.func_doc的时候得到的不是被修饰函数的相关信息而是装饰器wrapper函数的docstring和名字

对此我们使用functools这个模块添加一行函数即可


@functools.wraps(f)
def check_id_admin(f):
'''检查是否为admin'''
# 使得__name__和func_doc能够获得函数原有的docstring和函数名而不是装饰器相关的
@functools.wraps(f)
def wrapper(*args,**kwargs):
     if kwargs.get("username")!="admin":
raise Exception("this user is not allowed to get food!")
return f(*args,**kwargs)
return wrapper @check_id_admin
def get_food(username,password,food="chocolate"):
'''get food'''
return "%s get food: %s"%(username,food) def main():
print(get_food.__name__)
print(get_food.func_doc)
#输出结果:

get_food
  get food

 对比不使用@functools.wrap(f)

 wrapper

 none 

2.查看functools.wraps()源码


RAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
'__annotations__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
try:
     #在这里获取原函数wrapped的attr赋值给value
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(wrapper, attr, value)
for attr in updated:
     #用wrapped获取的值更新wrapper中的attr
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
# from the wrapped function when updating __dict__
wrapper.__wrapped__ = wrapped
# Return the wrapper so this can be used as a decorator via partial()
return wrapper def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)

从上面代码中可以看出wraps这个函数是通过partial和update_wrapper来实现的

(1)update_wrapper函数

update_wrapper做的工作很简单,就是用参数wrapped表示的函数对象(例如:square)的一些属性()如:__name__、 __doc__)覆盖参数wrapper表示的函数对象的这些相应属性.

即先保存被更新函数信息再更新到新函数中再返回给调用者。

(2)partial函数

简单总结functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。上代码:

from functools import partial

def add(a,b,c):
return a+b+c
#固定bc两个参数->add_one仅需要一个参数a
add_one = partial(add,b=1,c=3)
#固定a参数->add_two不需要参数运算
add_two = partial(add_one,a=2)
print(add_one(a=3))
print(add_two())

因此

#返回一个参数给定的update_wrapper函数
return partial(update_wrapper, wrapped=wrapped,assigned=assigned, updated=updated)

[python 基础]python装饰器(一)添加functools获取原函数信息以及functools.partial分析的更多相关文章

  1. python基础—函数装饰器

    python基础-函数装饰器 1.什么是装饰器 装饰器本质上是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能. 装饰器的返回值是也是一个函数对象. 装饰器经常用于有切 ...

  2. 十. Python基础(10)--装饰器

    十. Python基础(10)--装饰器 1 ● 装饰器 A decorator is a function that take a function as an argument and retur ...

  3. Day11 Python基础之装饰器(高级函数)(九)

    在python中,装饰器.生成器和迭代器是特别重要的高级函数   https://www.cnblogs.com/yuanchenqi/articles/5830025.html 装饰器 1.如果说装 ...

  4. 1.16 Python基础知识 - 装饰器初识

    Python中的装饰器就是函数,作用就是包装其他函数,为他们起到修饰作用.在不修改源代码的情况下,为这些函数额外添加一些功能,像日志记录,性能测试等.一个函数可以使用多个装饰器,产生的结果与装饰器的位 ...

  5. [python基础]关于装饰器

    在面试的时候,被问到装饰器,在用的最多的时候就@classmethod ,@staticmethod,开口胡乱回答想这和C#的static public 关键字是不是一样的,等面试回来一看,哇,原来是 ...

  6. python基础之 装饰器,内置函数

    1.闭包回顾 在学习装饰器之前,可以先复习一下什么是闭包? 在嵌套函数内部的函数可以使用外部变量(非全局变量)叫做闭包! def wrapper(): money =10 def inner(num) ...

  7. python基础之装饰器(实例)

    1.必备 #### 第一波 #### def foo(): print 'foo' foo #表示是函数 foo() #表示执行foo函数 #### 第二波 #### def foo(): print ...

  8. 学习PYTHON之路, DAY 5 - PYTHON 基础 5 (装饰器,字符格式化,递归,迭代器,生成器)

    ---恢复内容开始--- 一 装饰器 1 单层装饰器 def outer(func): def inner(): print('long') func() print('after') return ...

  9. python基础-----函数/装饰器

    函数 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 函数的优点之一是,可以将代码块与主程 ...

随机推荐

  1. 挂载硬盘,提示 mount: unknown filesystem type 'LVM2_member'的解决方案

    问题现象:由于重装linux,并且加了固态硬盘,直接将系统装在固态硬盘中.启动服务器的时候, 便看不到原来机械硬盘的挂载目录了,不知如何访问机械硬盘了.直接用命令 mount /dev/sda3 /s ...

  2. strut2 拦截器 使用

    拦截器是strut2里一个很振奋人心的应用.通过配置拦截器可以在action执行之前进行一些初始化或者是其他的操作,但是在action执行之后,返回结果就已经确定,结果是很难改变了(目前我还不知道怎么 ...

  3. ProE常用曲线方程:Python Matplotlib 版本代码(蝴蝶曲线)

    花纹的生成可以使用贴图的方式,同样也可以使用方程,本文列出了几种常用曲线的方程式,以取代贴图方式完成特定花纹的生成. 注意极坐标的使用................. 前面部分基础资料,参考:Pyt ...

  4. k[原创]Faster R-CNN论文翻译

    物体检测论文翻译系列: 建议从前往后看,这些论文之间具有明显的延续性和递进性. R-CNN SPP-net Fast R-CNN Faster R-CNN Faster R-CNN论文翻译   原文地 ...

  5. (转)Hibernate关联映射——一对多(多对一)

    http://blog.csdn.net/yerenyuan_pku/article/details/70152173 Hibernate关联映射——一对多(多对一) 我们以客户(Customer)与 ...

  6. if判断,while循环,for循环

    if判断 if判断其实就是让计算机模拟人的判断 if if 条件: 代码1 代码2 代码3 ... # 代码块(同一缩进级别的代码,例如代码1.代码2和代码3是相同缩进的代码,这三个代码组合在一起就是 ...

  7. openstack——horizon篇

    一.horizon 介绍:       理解 horizon   Horizon 为 Openstack 提供一个 WEB 前端的管理界面 (UI 服务 )通过 Horizone 所提供的 DashB ...

  8. Netty 长连接服务

    转自:https://www.dozer.cc/2014/12/netty-long-connection.html 推送服务 还记得一年半前,做的一个项目需要用到 Android 推送服务.和 iO ...

  9. 《啊哈算法》中P81解救小哈

    题目描述 首先我们用一个二维数组来存储这个迷宫,刚开始的时候,小哼处于迷宫的入口处(1,1),小哈在(p,q).其实这道题的的本质就在于找从(1,1)到(p,q)的最短路径. 此时摆在小哼面前的路有两 ...

  10. PHP中的几个随机数生成函数

    PHP中的几个随机数生成函数 rand() 基于 libc 的随机种子发生器 mt_rand() 基于 Mersenne Twister 算法返回随机整数.它可以产生随机数值的平均速度比 libc 提 ...