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

  • 相关阅读:
    SQL Server -使用表触发器记录表插入,更新,删除行数
    利用DataSet部分功能实现网站登录
    SQL Server排序的时候使null值排在最后
    大数据操作:删除和去重
    C#匿名类型序列化、反序列化
    Js调用asp.net后台代码
    C# Excel
    ajax的介绍
    MySQL数据库的知识总结
    ASP.NET MVC 入门系列教程
  • 原文地址:https://www.cnblogs.com/yupeng/p/3432532.html
Copyright © 2011-2022 走看看