[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语句返回. 函数的优点之一是,可以将代码块与主程 ...
随机推荐
- C语言保留字
数值变量相关: int float double char long short unsigned signed 储存说明符 const 用于声明常量 static用于限制变量/函数的作用范围等等 e ...
- (Entity framework 应用篇)把权限判断封装在数据库访问层
这里,我只是以一个例子,说一下简单权限控制,通过这个例子,大家可以设计庞大的权限管理层,把权限控制封装到数据库访问层,这样程序员就不用再写权限判断的代码了 首先,先看看我数据库DBContext的定义 ...
- IntentService和HandlerThread的使用以及源码阅读
使用MyIntentService.java public class MyIntentService extends IntentService { /** * 是否正在运行 */ private ...
- LDAP个人理解
在新的公司办公,所有的后台系统或文档系统都公用一个LDAP账号. 接触到这个新名词,就查了一下,谈谈个人理解: LDAP是个协议, 简单地说,可以把LDAP服务理解为一套存放你账户密码的数据库系统.市 ...
- js 输入框只能输入 1-7 的数字
$jq(function () { $jq("#XSCM_WORKDAY").keyup(function () { //如果输入非数字,则替换为'',如果输入数字,则在每4位之后 ...
- hstack()与vstack()函数
ref: https://blog.csdn.net/csdn15698845876/article/details/73380803 1. hstack()函数 a,b只有一个维度:对第一个维度拼接 ...
- vue数据绑定源码
思路分析 数据的双向绑定,就是数据变化了自动更新视图,视图变化了自动更新数据,实际上视图变化更新数据只要通过事件监听就可以实现了,并不是数据双向绑定的关键点.关键还是数据变化了驱动视图自动更新. 所有 ...
- odoo api介绍
odoo api修饰器介绍与应用 参考文档:https://www.cnblogs.com/kfx2007/p/6093994.html 一.one one的用法主要用于self为单一集合的情况,被o ...
- How to start a pdf reader from a Linux command line?
Before you do this, you should be in a GOME or KDE environment, then type the following commands to ...
- 【codeforces 767D】Cartons of milk
[题目链接]:http://codeforces.com/problemset/problem/767/D [题意] 每个牛奶都有最晚可以喝的时间; 每天喝K瓶牛奶; 你有n瓶牛奶->已知每个牛 ...