[python 基础]python装饰器(一)添加functools获取原函数信息以及functools.partial分析
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分析的更多相关文章
- python基础—函数装饰器
python基础-函数装饰器 1.什么是装饰器 装饰器本质上是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能. 装饰器的返回值是也是一个函数对象. 装饰器经常用于有切 ...
- 十. Python基础(10)--装饰器
十. Python基础(10)--装饰器 1 ● 装饰器 A decorator is a function that take a function as an argument and retur ...
- Day11 Python基础之装饰器(高级函数)(九)
在python中,装饰器.生成器和迭代器是特别重要的高级函数 https://www.cnblogs.com/yuanchenqi/articles/5830025.html 装饰器 1.如果说装 ...
- 1.16 Python基础知识 - 装饰器初识
Python中的装饰器就是函数,作用就是包装其他函数,为他们起到修饰作用.在不修改源代码的情况下,为这些函数额外添加一些功能,像日志记录,性能测试等.一个函数可以使用多个装饰器,产生的结果与装饰器的位 ...
- [python基础]关于装饰器
在面试的时候,被问到装饰器,在用的最多的时候就@classmethod ,@staticmethod,开口胡乱回答想这和C#的static public 关键字是不是一样的,等面试回来一看,哇,原来是 ...
- python基础之 装饰器,内置函数
1.闭包回顾 在学习装饰器之前,可以先复习一下什么是闭包? 在嵌套函数内部的函数可以使用外部变量(非全局变量)叫做闭包! def wrapper(): money =10 def inner(num) ...
- python基础之装饰器(实例)
1.必备 #### 第一波 #### def foo(): print 'foo' foo #表示是函数 foo() #表示执行foo函数 #### 第二波 #### def foo(): print ...
- 学习PYTHON之路, DAY 5 - PYTHON 基础 5 (装饰器,字符格式化,递归,迭代器,生成器)
---恢复内容开始--- 一 装饰器 1 单层装饰器 def outer(func): def inner(): print('long') func() print('after') return ...
- python基础-----函数/装饰器
函数 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 函数的优点之一是,可以将代码块与主程 ...
随机推荐
- 【译】x86程序员手册10 - 第4章系统架构
1.1.2 Part II -- Systems Programming 系统编程 This part presents those aspects of the architecture that ...
- mybatis 简单的入门实例
第一步:添加mybaties的架包 第二步:配置mybaties的文件 <?xml version="1.0" encoding="UTF-8" ?> ...
- POJ 3984 迷宫问题 (BFS + Stack)
链接 : Here! 思路 : BFS一下, 然后记录下每个孩子的父亲用于找到一条路径, 因为寻找这条路径只能从后向前找, 这符合栈的特点, 因此在输出路径的时候先把目标节点压入栈中, 然后不断的向前 ...
- 03.requests模块(1)
目录 03.requests模块(1) 展开requests模块的学习 代码实例 需求:爬取搜狗指定词条搜索后的页面数据 需求:登录豆瓣电影,爬取登录成功后的页面数据 需求:爬取豆瓣电影分类排行榜 h ...
- elisp 编程 if 特殊表
elisp中的 if 特殊表与其他语言中的 if 语句逻辑上并无二致,关键在于如何使用. (if (> 4 3) (message "4 is greater than 3" ...
- PAT 1119 Pre- and Post-order Traversals
Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can ...
- 实验十二 团队作业8:软件测试与Alpha冲刺 第四天
项目 内容 这个作业属于哪个课程 老师链接 这个作业的要求在哪里 实验十二 团队作业8:软件测试与Alpha冲刺 团队名称 Always Run! 作业学习目标 (1)掌握软件测试基础技术 (2)学习 ...
- hadoop-hdp-ambari离线安装记录
一.系统准备 1. 创建user——ambari 2.关闭防火墙 redhat6: chkconfig iptables off /etc/init.d/iptables stop redhat7: ...
- RestEasy 用户指南----第4章.使用@Path @GET @POST 等
转载说明出处:http://blog.csdn.net/nndtdx/article/details/6870391 原文地址 http://docs.jboss.org/resteasy/docs/ ...
- DOM对象属性(property)与HTML标签特性(attribute)
HTML中property与attribute是极易混淆的两个概念.大多数时候这两个单词都翻译为"属性",为了区分二者,一般将property翻译为"属性",a ...