天天看點

python——函數——高階函數

高階函數

高階函數,higher-order function,是比普通函數更高層次的抽象,包括:

  • 參數為函數
  • 傳回值為函數

嵌套函數

def arith(a, b, op):
    def add(a, b):
        print a, '+', b, '=', a + b

    def sub(a, b):
        print a, '-', b, '=', a - b

    def mul(a, b):
        print a, '*', b, '=', a * b

    def div(a, b):
        print a, '/', b, '=', a / b
        
    if op == '+':
        add(a, b)
    elif op == '-':
        sub(a, b)
    elif op == '*':
        mul(a, b)
    elif op == '/':
        div(a, b)

arith(18, 8, '+')
arith(18, 8, '-')
arith(18, 8, '*')
arith(18, 8, '/')
           

output:

18 + 8 = 26
18 - 8 = 10
18 * 8 = 144
18 / 8 = 2
           

總結:

  • 函數本質是對象,無論嵌套函數還是普通函數,是以嵌套函數定義與普通函數定義無差別,都是定義函數對象
  • 嵌套函數定義相當于外圍函數對象内定義函數對象(嵌套函數),是以嵌套函數隻對其外圍函數可見

參數為函數

def add(a, b):
    print a, '+', b, '=', a + b

def sub(a, b):
    print a, '-', b, '=', a - b

def mul(a, b):
    print a, '*', b, '=', a * b

def div(a, b):
    print a, '/', b, '=', a / b

def arith(fun, a, b):
    fun(a, b)

arith(add, 18, 8)
arith(sub, 18, 8)
arith(mul, 18, 8)
arith(div, 18, 8)
           

output:

18 + 8 = 26
18 - 8 = 10
18 * 8 = 144
18 / 8 = 2
           

傳回值為函數

def arith(op):
    def add(a, b):
        print a, '+', b, '=', a + b

    def sub(a, b):
        print a, '-', b, '=', a - b

    def mul(a, b):
        print a, '*', b, '=', a * b

    def div(a, b):
        print a, '/', b, '=', a / b
        
    if op == '+':
        return add
    elif op == '-':
        return sub
    elif op == '*':
        return mul
    elif op == '/':
        return div

add = arith('+')
sub = arith('-')
mul = arith('*')
div = arith('/')

add(18, 8)
sub(18, 8)
mul(18, 8)
div(18, 8)
           

output:

18 + 8 = 26
18 - 8 = 10
18 * 8 = 144
18 / 8 = 2