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. Hive扩展功能(八)--表的索引

    软件环境: linux系统: CentOS6.7 Hadoop版本: 2.6.5 zookeeper版本: 3.4.8 主机配置: 一共m1, m2, m3这三部机, 每部主机的用户名都为centos ...

  2. JS——indexOf replace search

    indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置 注释:indexOf() 方法对大小写敏感!如果要检索的字符串值没有出现,则该方法返回 -1. 语法:searchvalue, ...

  3. 控制台——args参数的赋值方法

    args参数的赋值方法有好几种,主要介绍两种. 外部传参的方法:先找到bin目录下的exe文件,并创建快捷方法,在目标后面追加参数. 控制台主函数入口实现方法 static void Main(str ...

  4. 使用NSSM将Kibana安装为Windows服务

    Kibana不同于Elasticsearch,前者官方并没有提供安装为系统服务的方法,如果直接运行在生产环境中会尤为麻烦,一旦服务器因故重启就要手动开启,所以将Kibana安装为系统服务非常有必要. ...

  5. HDU_1087_Super Jumping! Jumping! Jumping!_dp

    Super Jumping! Jumping! Jumping! Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 ...

  6. pandas写入多组数据到excel不同的sheet

    今天朋友问了我个需求,就是如何将多个分析后的结果,也就是多个DataFrame,写入同一个excel工作簿中呢? 之前我只写过放在一个sheet中,但是怎么放在多个sheet中呢?下面我在本地wind ...

  7. enote笔记语言(4)(ver0.4)——“5w1h2k”分析法

    章节:“5w1h2k”分析法   what:我想知道某个“关键词(keyword)”(即,词汇.词语,或称单词,可以是概念|专业术语|.......)的定义. why:我想分析and搞清楚弄明白“事物 ...

  8. 小实例 hangman game

    代码 #include <bits/stdc++.h> using namespace std; int bk[110]; string sj(int t) { string ans=&q ...

  9. Linux之网络文件共享服务(FTP)

    一.FTP概念 •File Transfer Protocol 早期的三个应用级协议之一 •基于C/S结构 •双通道协议:数据和命令连接 •数据传输格式:二进制(默认)和文本  •两种模式:服务器角度 ...

  10. array_map 等php回调函数使用问题(关联数组下标获取)

    前言:我自己用此类回调函数,来替代 foreach 纯粹是用为代码的简洁性,让代码更好看.(我有点代码小洁癖~) 1.array_reduce 当迭代处理一个一维索引数组时,在回调函数内是无法获取到当 ...