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

  只能寫在一行上,表達式的結果就是返回值對象

  匿名函數遞歸依賴於最初賦值的變量名,因此最好不要遞歸遞歸

相關文章
相關標籤/搜索