Python3函数之高阶函数、匿名函数

高阶函数

  参数是函数,返回值也是函数python

  易于可读性,方便代码维护,隔离做用域闭包

  函数是一等对象

def sort(lst, cmp=None, reverse=False):
    def default_cmp(a, b): # 对函数参数进行设置默认值
        if a > b:
            return 1     # 当没有传入函数参数时
        if a == b:
            return 0
        if a < b:       # 可使用函数内的函数
            return -1
    if cmp is None: 
        cmp = default_cmp  # 函数是一等对象的一个体现
    dst = []
    for n in lst:
        for i, e in enumerate(dst):
            if not reverse:
                if cmp(n, e) < 0:
                    dst.insert(i, n)
                    break
            else:
                if cmp(n, e) > 0:
                    dst.insert(i, n)
                    break
        else:
            dst.append(n)
    return dst

    闭包的python形式

def make_counter(init):
    counter = [init]  # 直接引用init,返回函数的时候不会保存counter,会出错
    def inc():
        counter[0] += 1 # 因此python2并非真正意义上的闭包
    def dec():
        counter[0] -= 1
    def get():
        return counter[0]
    def reset():
        counter[0] = init
    return inc, dec, get, reset

  返回的四个函数在上一级做用域make_counter结束的后,仍能使用做用域里的变量app

def make_counter(init):
    counter = init
    def inc():
        nonlocal counter  # python3使用nonlocal概念,真正的闭包
        counter += 1
    def dec():
        nonlocal counter # 标识不是本做用域的变量,已经被定义,
        counter -= 1 # 去上一级做用域引用
    def get():
        nonlocal counter # 对于列表,至关于可变参数
        return counter
    def reset():
        nonlocal counter # 只初始化一次
        counter = init
    return inc, dec, get, reset

  偏函数

  固定参数,即固定参数的一种功能,生成单一新函数函数

from functools import partial
hex_to_int = partial(int, base=16) # 固定int的base关键字参数为16
hex_to_int('0xAAAA')

  柯里化

匿名函数

  lambda params : exprspa

  没有函数名称,须要经过赋值code

  只能写在一行上,表达式的结果就是返回值对象

  匿名函数递归依赖于最初赋值的变量名,因此最好不要递归递归

相关文章
相关标签/搜索