一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python中partial函数用法

时间:2016-07-28 编辑:简简单单 来源:一聚教程网

函数的partial应用

函数在执行时,要带上所有必要的参数进行调用。但是,有时参数可以在函数被调用之前提前获知。这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。

例子

 代码如下 复制代码

>> from operator import add, mul
>>> from functools import partial
>>> add1 = partial(add, 1)
# add1(x) == add(1, x)
>>> mul100 = partial(mul, 100) # mul100(x) == mul(100, x)
>>>
>>> add1(10)
11
>>> add1(1)
2
>>> mul100(10)
1000
>>> mul100(500)

有些时候这样的操作让我们能够更加清晰的展示我们的程序

例如:

 代码如下 复制代码

In [9]: from functools import partial

In [10]: def add(a,b):
....: return a+b
....:

In [11]: add(4,3)
Out[11]: 7

In [12]: plus = partial(add,100)

In [13]: plus(9)
Out[13]: 109

In [14]: plus2 = partial(add,99)

In [15]: plus2(9)
Out[15]: 108

其实就是函数调用的时候,有多个参数 参数,但是其中的一个参数已经知道了,我们可以通过这个参数重新绑定一个新的函数,然后去调用这个新函数。

如果有默认参数的话,他们也可以自动对应上,例如:

 代码如下 复制代码

In [17]: def add2(a,b,c=2):
....: return a+b+c
....:

In [18]: plus3 = partail(add,101)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/yupeng/Documents/PhantomJS/ in ()
----> 1 plus3 = partail(add,101)

NameError: name 'partail' is not defined

In [19]: plus3 = partial(add,101)

In [20]: plus3(1)
Out[20]: 102

In [21]: plus3 = partial(add2,101)

In [22]: plus3 = partial(add2,101) (1)
Out[22]: 104

In [23]: plus3(1)
Out[23]: 104

In [24]: plus3(1,2)
Out[24]: 104

In [25]: plus3(1,3)
Out[25]: 105

In [26]: plus3(1,30)
Out[26]: 132

partial改变方法默认参数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#python2.7x
#partial.py
#authror: orangleliu
 
'''
functools 中Partial可以用来改变一个方法默认参数
1 改变原有默认值参数的默认值
2 给原来没有默认值的参数增加默认值
'''
def foo(a,b=0) :
  '''
  int add'
  '''
  print a + b
 
#user default argument
foo(1)
 
#change default argument once
foo(1,1)
 
#change function's default argument, and you can use the function with new argument
import functools
 
foo1 = functools.partial(foo, b=5) #change "b" default argument
foo1(1)
 
foo2 = functools.partial(foo, a=10) #give "a" default argument
foo2()
 
'''
foo2 is a partial object,it only has three read-only attributes
i will list them
'''
print foo2.func
print foo2.args
print foo2.keywords
print dir(foo2)
 
##默认情况下partial对象是没有 __name__ __doc__ 属性,使用update_wrapper 从原始方法中添加属性到partial 对象中
print foo2.__doc__
'''
执行结果:
partial(func, *args, **keywords) - new function with partial application
  of the given arguments and keywords.
'''
 
functools.update_wrapper(foo2, foo)
print foo2.__doc__
'''
修改为foo的文档信息了
'''

这样如果我们使用一个方法总是需要默认几个参数的话就可以,先做一个封装然后不用每次都设置相同的参数了。

热门栏目