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. 15、Scala隐式转换和隐式参数

    1.隐式转换 2.使用隐式转换加强现有类型 3.隐式转换函数的作用域与导入 4.隐式转换发生时机 5.隐式参数 1.隐式转换 要实现隐式转换,只要程序可见的范围内定义隐式转换函数即可.Scala会自动 ...

  2. spring+spring MVC+mybatis 框架搭建

    1.新建一个javaWeb工程Test,创建时记得勾选web.xml文件. 2.导入需要的jar包,Mybatis所有的jar,spring所有的jar,mysql驱动包. 这里mybatis和spr ...

  3. 文章或者观点说说等点赞功能实现(thinkphp)

    前端的代码: <!-- 点赞 --> <div class='btm'><a class='zan' id="{$article.id}" href= ...

  4. API开发管理平台eoLinker AMS 4.1版本发布:加入聚合空间,发布AMS专业版等

    eoLinker AMS是集API文档管理.API自动化测试.开发协作三位一体的综合API开发管理平台,是中国最大的在线API管理平台. eoLinker AMS 4.1更新内容: 1.新增" ...

  5. Eclipse安装和使用TFS

    第一步下载Tfs插件 去微软官网下载https://www.microsoft.com/en-us/download/details.aspx?id=4240 点击 选择下载 随便放置到一个本地或者服 ...

  6. Delphi / Pascal 语法知识干货

    ********************************************* Pascal.Delph干货 *************************************** ...

  7. 3.filter原理(bitset机制与caching机制)

    主要知识点: 一次filter执行顺序 filter和query的特点     一.一次filter执行顺序     1.在倒排索引中查找搜索串,获取document list 以一下date数据来举 ...

  8. CentOS7下安装ELK三件套

    ELK用于分布式收集,然后elasticsearch用于分析数据,在Kibana中可以查看数据.报表. 目前公司日志数据量暂时不使用elasticsearch集群,只是用的elasticsearch单 ...

  9. Maven学习总结(10)——使用Maven编译项目gbk的不可映射问题

    Maven学习总结(十)--使用Maven编译项目gbk的不可映射问题 一.问题描述 今天在MyEclipse中使用Maven编译项目源代码时,结果如下了如下的错误 百思不得其解啊,java源代码在M ...

  10. MAC OS下JDK版本切换指南

    刚上手的用MAC开发的小伙伴们会发现,MAC自带JDK版本为1.6,通常会安装在 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/目录下,但是更多 ...