CS61A pyhton----高阶函数/lambda


CS61A pyhton----高阶函数

A function that either:

  • Takes another function as an argument
  • Returns a function as its result

All other functions are considered first-order functions.

可以直接将函数名当成参数传入函数

def cube(k):
    return k ** 3

def summation(n, term):
    """Sum the first N terms of a sequence.
    >>> summation(5, cube)
    225
    """
    total = 0
    k = 1
    while k <= n:
        total = total + term(k)
        k = k + 1
    return total

可以在函数中直接定义函数,此时子函数的域绑定在母函数下

人话:母函数中的变量子函数也可以用

lambda

lambda :

sq = lambda x : x * x
# sq(3) 9

条件表达式

if else

lambda x: x if x > 0 else 0

多环境

环境指的是一系列的 frame

当一个name被提及时,python会找当前环境下最近的frame