Python中functools模块的常用函数解析

yipeiwu_com5年前Python基础

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__ 
 
print 
 
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>]

相关文章

在Python的Flask框架中验证注册用户的Email的方法

在Python的Flask框架中验证注册用户的Email的方法

本教程详细介绍在用户注册过程中如何去验证他们的email地址。 工作流程上来讲,在用户注册一个新账户后会寄送一个确认信。直到用户按指示完成了邮件中的“验证”,否则他们的账户会一直处于“未...

python中PIL安装简单教程

python 的PIL安装是一件很头疼的的事, 如果你要在python 中使用图型程序那怕只是将个图片从二进制流中存盘(例如使用Scrapy 爬网存图),那么都会使用到 PIL 这库,而...

Python命令行解析模块详解

本文研究的主要是Python命令行解析模块的相关内容,具体如下。 Python命令行常见的解析器有两种,一是getopt模块,二是argparse模块。下面就解读下这两种解析器。 ge...

Python计算开方、立方、圆周率,精确到小数点后任意位的方法

Python计算开方、立方、圆周率,精确到小数点后任意位的方法

Python计算的位数 在电脑上做了一个实验,看看python能计算到多少位,一下是结果。 x = math.sqrt((3)) print ("%.53f"%(x)) print...

Python 编程速成(推荐)

Python是一种非常流行的脚本语言,而且功能非常强大,几乎可以做任何事情,比如爬虫、网络工具、科学计算、树莓派、Web开发、游戏等各方面都可以派上用场。同时无论在哪种平台上,都可以用...