Python常用模块之四 funsctools

functools 模块中有三个主要的函数 partial(), update_wrapper() 和 wraps()。

1、partial(func[,args][, *keywords])

  functools.partial 通过包装手法,允许我们 "重新定义" 函数签名。用一些默认参数包装一个可调用对象,返回结果是可调用对象,并且可以像原始对象一样对待冻结部分函数位置函数或关键字参数,简化函数,更少更灵活的函数参数调用。

from functools import partial
int2 = partial(int, base=2)

print int2(‘11‘) # 3
print int2(‘101‘) # 5

当函数的参数个数太多,需要简化时,使用functools.partial可以创建一个新的函数,这个新函数可以固定住原函数的部分参数,从而在调用时更简单。

2、functool.update_wrapper

  默认partial对象没有__name__和__doc__, 这种情况下,对于装饰器函数非常难以debug.使用update_wrapper(),从原始对象拷贝或加入现有partial对象。它可以把被封装函数的__name__、module、__doc__和 __dict__都复制到封装函数去(模块级别常量WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)。

  这个函数主要用在装饰器函数中,装饰器返回函数反射得到的是包装函数的函数定义而不是原始函数定义

>>> functools.WRAPPER_ASSIGNMENTS
(‘__module__‘, ‘__name__‘, ‘__doc__‘)
>>> functools.WRAPPER_UPDATES
(‘__dict__‘,)
#!/usr/bin/env python
# encoding: utf-8

def wrap(func):
    def call_it(*args, **kwargs):
        """wrap func: call_it"""
        print ‘before call‘
        return func(*args, **kwargs)
    return call_it

@wrap
def hello():
    """say hello"""
    print ‘hello world‘

from functools import update_wrapper
def wrap2(func):
    def call_it(*args, **kwargs):
        """wrap func: call_it2"""
        print ‘before call‘
        return func(*args, **kwargs)
    return update_wrapper(call_it, func)

@wrap2
def hello2():
    """test hello"""
    print ‘hello world2‘

if __name__ == ‘__main__‘:
    hello()
    print hello.__name__
    print hello.__doc__

    print
    hello2()
    print hello2.__name__
    print hello2.__doc__

结果:
before call
hello world
call_it
wrap func: call_it

before call
hello world2
hello2
test hello

3、functool.wraps

调用函数装饰器partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)的简写。

from functools import wraps
def wrap3(func):
    @wraps(func)
    def call_it(*args, **kwargs):
        """wrap func: call_it2"""
        print ‘before call‘
        return func(*args, **kwargs)
    return call_it

@wrap3
def hello3():
    """test hello 3"""
    print ‘hello world3‘

结果:
before call
hello world3
hello3
test hello 3

详见:http://www.wklken.me/posts/2013/08/18/python-extra-functools.html

时间: 2024-12-17 02:26:24

Python常用模块之四 funsctools的相关文章

python——常用模块

time.asctime(time.localtime(1234324422)) python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行"type(time.time())",返回的是float类型.

实战篇一 python常用模块和库介绍

# [email protected] coding: utf-8 [email protected] -- Python 常用模块和库介绍 第一部分:json模块介绍 import json 将一个Python数据结构转换为JSON: dict_ = {1:2, 3:4, "55":"66"} # test json.dumps print type(dict_), dict_ json_str = json.dumps(dict_) print "js

python——常用模块2

python--常用模块2 1 logging模块 1.1 函数式简单配置 import logging logging.debug("debug message") logging.info("info message") logging.warning("warning message") logging.error("error message") logging.critical('critical message')

Python常用模块-随机数模块(random)

Python常用模块-随机数模块(random) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.常用方法举例 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7

Python常用模块-摘要算法(hashlib)

Python常用模块-摘要算法(hashlib) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.MD5算法参数详解 1.十六进制md5算法摘要 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%

python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess logging re正则 转自老男孩老师Yuan:http://www.cnblogs.com/yuanchenqi/articles/5732581.html 模块&包(* * * * *) 模块(modue)的概念: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,

python常用模块之time&datetime模块

python常用模块之time&datetime模块 在平常的代码中,我们经常要与时间打交道.在python中,与时间处理有关的模块就包括:time和datetime,下面分别来介绍: 在开始之前,首先要说明有以下几种方式来表示时间: 1.时间戳 2.格式化的时间字符串(时间对象) 3.元组(struct_time)共九个元素,由于python的time模块实现主要调用C库,所以各个平台可能不同 几个定义 UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文

Python常用模块——系统调用os模块

Python常用模块--系统调用os模块 OS模块 os模块提供了很多允许你的程序与操作系统直接交互的功能. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录:os.removedirs(r"c:\python") 检验给出的路径是否是一个文件:os.path.isfile() 检验给出的路径是否是一个目录:os.path.isdir(

Python常用模块——系统调用sys模块

Python常用模块--系统调用sys模块 sys 模块 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序的版本信息 sys.maxint 最大的Int值 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform 返回操作系统平台名称 sys.stdout.write('please:') #标准输出 , 引出进度条的例子