Python functools模块学习总结

 更新时间:2015年05月09日 12:02:36   投稿:junjie  
这篇文章主要介绍了Python functools模块学习总结,本文讲解了functools.partial、functool.update_wrapper、functool.wraps、functools.reduce、functools.cmp_to_key、functools.total_ordering等方法的使用实例,需要的朋友可以参考下

文档 地址

functools.partial

作用:

functools.partial 通过包装手法,允许我们 "重新定义" 函数签名

用一些默认参数包装一个可调用对象,返回结果是可调用对象,并且可以像原始对象一样对待

冻结部分函数位置函数或关键字参数,简化函数,更少更灵活的函数参数调用

复制代码 代码如下:

#args/keywords 调用partial时参数
def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords) #合并,调用原始函数,此时用了partial的参数
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

声明:
复制代码 代码如下:

urlunquote = functools.partial(urlunquote, encoding='latin1')

当调用 urlunquote(args, *kargs)

相当于 urlunquote(args, *kargs, encoding='latin1')

E.g:

复制代码 代码如下:

import functools

def add(a, b):
    return a + b

add(4, 2)
6

plus3 = functools.partial(add, 3)
plus5 = functools.partial(add, 5)

plus3(4)
7
plus3(7)
10

plus5(10)
15

应用:

典型的,函数在执行时,要带上所有必要的参数进行调用。

然后,有时参数可以在函数被调用之前提前获知。

这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。

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

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

functools.reduce

复制代码 代码如下:

functools.reduce(function, iterable[, initializer])

等同于内置函数reduce()

用这个的原因是使代码更兼容(python3)

functools.cmp_to_key

functools.cmp_to_key(func)
将老式鼻尖函数转换成key函数,用在接受key函数的方法中(such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby())

一个比较函数,接收两个参数,小于,返回负数,等于,返回0,大于返回整数

key函数,接收一个参数,返回一个表明该参数在期望序列中的位置

例如:

复制代码 代码如下:

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

functools.total_ordering

复制代码 代码如下:

functools.total_ordering(cls)

这个装饰器是在python2.7的时候加上的,它是针对某个类如果定义了__lt__、le、gt、__ge__这些方法中的至少一个,使用该装饰器,则会自动的把其他几个比较函数也实现在该类中
复制代码 代码如下:

@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
print dir(Student)

得到
复制代码 代码如下:

['__doc__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__', '__module__']

相关文章

  • 全面理解python命名空间字典

    全面理解python命名空间字典

    本文主要介绍了全面理解python命名空间字典,python的命名空间由字典实现,属性为键,对象为值,通过属性找到对象,下面就来具体了解一下,感兴趣的可以了解一下
    2023-12-12
  • python多线程使用方法实例详解

    python多线程使用方法实例详解

    这篇文章主要介绍了python多线程使用方法,结合实例形式详细分析了Python多线程thread模块、锁机制相关使用技巧与操作注意事项,需要的朋友可以参考下
    2019-12-12
  • Python获取当前公网ip并自动断开宽带连接实例代码

    Python获取当前公网ip并自动断开宽带连接实例代码

    这篇文章主要介绍了Python获取当前公网ip并自动断开宽带连接实例代码,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 深入了解如何基于Python读写Kafka

    深入了解如何基于Python读写Kafka

    这篇文章主要介绍了深入了解如何基于Python读写Kafka,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • PyCharm提示No Python Interpreter的正确解决办法

    PyCharm提示No Python Interpreter的正确解决办法

    刚学Python时,拿到一个Python项目,想用pycharm打开运行却报错了,这篇文章主要给大家介绍了关于PyCharm提示No Python Interpreter的正确解决办法,需要的朋友可以参考下
    2023-10-10
  • 浅谈pytorch中为什么要用 zero_grad() 将梯度清零

    浅谈pytorch中为什么要用 zero_grad() 将梯度清零

    这篇文章主要介绍了pytorch中为什么要用 zero_grad() 将梯度清零的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • python数字图像处理像素的访问与裁剪示例

    python数字图像处理像素的访问与裁剪示例

    这篇文章主要为大家介绍了python数字图像处理像素的访问与裁剪示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • Python functools冻结参数小技巧实现代码简洁优化

    Python functools冻结参数小技巧实现代码简洁优化

    这篇文章主要为大家介绍了Python functools冻结参数小技巧实现代码简洁优化示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • python字典如何获取最大和最小value对应的key

    python字典如何获取最大和最小value对应的key

    这篇文章主要介绍了python字典如何获取最大和最小value对应的key问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • Python OpenCV实现图形检测示例详解

    Python OpenCV实现图形检测示例详解

    图形检测在计算机视觉开发中是一项非常重要的操作,算法通过对图像的检测,分析出图像中可能存在哪些形状。本文详细介绍了Python+OpenCV如何实现图形检测,感兴趣的可以了解一下
    2022-04-04

最新评论