zoukankan      html  css  js  c++  java
  • python 中偏函数 partial 的使用

    函数的partial应用

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

    例如:

    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/<ipython-input-18-d4b7c6a6855d> in <module>()
    ----> 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

  • 相关阅读:
    kerberos系列之zookeeper的认证配置
    kafka概念扫盲
    linux不常用命令
    linux环境安装pip
    Hbase概念原理扫盲
    python语言中三个奇妙的返回值
    python通过http(multipart/form-data)上传文件的方法
    tp5.1 模型设置了软删除,detach 不能删除中间表的问题
    tp5.1 where in 写法
    tp 5.1 使用模型查询结果集插入另一个模型的问题
  • 原文地址:https://www.cnblogs.com/yupeng/p/3432532.html
Copyright © 2011-2022 走看看