Python中functools模块的常用函数解析
作者:wyabc1986 发布时间:2022-08-12 08:10:50
标签:Python,functools
1.partial
首先是partial函数,它可以重新绑定函数的可选参数,生成一个callable的partial对象:
>>> int('10') # 实际上等同于int('10', base=10)和int('10', 10)
10
>>> int('10', 2) # 实际上是int('10', base=2)的缩写
2
>>> from functools import partial
>>> int2 = partial(int, 2) # 这里我没写base,结果就出错了
>>> int2('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> int2 = partial(int, base=2) # 把base参数绑定在int2这个函数里
>>> int2('10') # 现在缺省参数base被设为2了
2
>>> int2('10', 3) # 没加base,结果又出错了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword parameter 'base' was given by position and by name
>>> int2('10', base=3)
3
>>> type(int2)
<type 'functools.partial'>
从中可以看出,唯一要注意的是可选参数必须写出参数名。
2.update_wrapper
接着是update_wrapper函数,它可以把被封装函数的__name__、__module__、__doc__和 __dict__都复制到封装函数去:
#-*- coding: gbk -*-
def thisIsliving(fun):
def living(*args, **kw):
return fun(*args, **kw) + '活着就是吃嘛。'
return living
@thisIsliving
def whatIsLiving():
"什么是活着"
return '对啊,怎样才算活着呢?'
print whatIsLiving()
print whatIsLiving.__doc__
from functools import update_wrapper
def thisIsliving(fun):
def living(*args, **kw):
return fun(*args, **kw) + '活着就是吃嘛。'
return update_wrapper(living, fun)
@thisIsliving
def whatIsLiving():
"什么是活着"
return '对啊,怎样才算活着呢?'
print whatIsLiving()
print whatIsLiving.__doc__
结果:
对啊,怎样才算活着呢?活着就是吃嘛。
None
对啊,怎样才算活着呢?活着就是吃嘛。
什么是活着
不过也没多大用处,毕竟只是少写了4行赋值语句而已。
3.wraps
再有是wraps函数,它将update_wrapper也封装了进来:
#-*- coding: gbk -*-
from functools import wraps
def thisIsliving(fun):
@wraps(fun)
def living(*args, **kw):
return fun(*args, **kw) + '活着就是吃嘛。'
return living
@thisIsliving
def whatIsLiving():
"什么是活着"
return '对啊,怎样才算活着呢?'
print whatIsLiving()
print whatIsLiving.__doc__
结果还是一样的:
对啊,怎样才算活着呢?活着就是吃嘛。
什么是活着
4.total_ordering
最后至于total_ordering函数则给予类丰富的排序方法,使用装饰器简化了操作。如果使用必须在类里面定义一个__lt__(),__le__(), __gt__(), 或__ge__()。应该给类添加一个__eq__() 方法。
from functools import total_ordering
@total_ordering
class Student(object):
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.lower() == other.name.lower()
def __lt__(self, other):
return self.name.lower() < other.name.lower()
a = Student('dan')
b = Student('mink')
print a > b
print a
print sorted([b, a])
打印结果
False
<__main__.Student object at 0x7f16ecb194d0>
[<__main__.Student object at 0x7f16ecb194d0>, <__main__.Student object at 0x7f16ecb195d0>]
0
投稿
猜你喜欢
- PHP添加图像处理(ImageMagick)下载地址:http://pecl.php.net/package/imagick安装说明:htt
- 今天遇到这个问题,上网查到以下解决方法:1.检查你的磁盘剩余空间是否足够,如果没有磁盘剩余空间,则清理磁盘,腾出空间
- 作者:Lachlan Hunt概要网络是不断的进化的. 新的和有创意的网站每天都在出现, 从各方面都在冲击着HTML的边界. HTML 4来
- ORA-00600:internal error code,arguments:[num],[?],[?],[?],[?]产生原因:这种错误
- 我在Web服务器端安装了Web Server IIS4.0、Oracle Net8 for Client,并创建好了和Oracle8数据库的
- javascript作为一个动态语言,动态解析脚本的方法非常多,如万恶又万能的eval,低调的Function,IE独占的execScrip
- 相信有些小伙伴,在没接触py之前,肯定都是有所准备的,想学语言由来已久,拿小编来说,一直趁着空挡就开始找课程学习,用记下学习历程,还会向一些
- 在前几篇博文中,我们分别采用颜色识别,模板匹配,像素遍历等方法实现了棋子和棋盘的定位,具体内容可以参见我的前面的文章内容,在这一篇中,我们来
- 简单来说python的内存管理机制有三种1)引用计数2)垃圾回收3)内存池接下来我们来详细讲解这三种管理机制1,引用计数:引用计
- windows版本下需要先安装ffmpeg工具:1:先下载指定(https://ffmpeg.zeranoe.com/builds/) 有S
- 下面是最终代码 (windows下实现的) # -*- coding: cp936 -*- import os path = 'D:
- 为了防止某些别有用心的人从外部访问数据库,盗取数据库中的用户姓名、密码、信用卡号等其他重要信息,在我们创建数据库驱动的解决方案时,我们首先需
- SCRIPT 标记 用于包含JavaScript代码. 属性 LANGUAGE&nbs
- 可以,具体方法如下::<% set fs=createobject("scripting.
- 看代码吧~import numpy as npa = np.array([[2, 4, 6, 1], [1, 5, 2, 9]])print
- Python的3.0版本,常被称为Python 3000,或简称Py3k。相对于Python的早期版本,这是一个较大的升级。为了不带入过多的
- <%'使用说明'Dim a'Set a=new CreateExce
- 作者:bencalie 整理日期:2004年6月15日<xml id="users"> <u
- DreamWeaver 4的到来让大家兴奋吧?但是大家一定为DreamWeaver4里面的字体、文字大
- 问:怎样解决MySQL 5.0.16的乱码问题?答:MySQL 5.0.16的乱码问题可以用下面的方法解决:1.设置phpMyAdminLa