闭包与Lambda

闭包与Lambda #

内联函数 #

内联函数即函数中声明函数。

def outter():
    print('outter')

    def inner():
        print('inner')
    inner()

outter()

内联函数只能在外部函数内调用,无法再外部函数外调用。

Lambda #

Python 中 Lambda 表达式其实就是匿名函数。

创建 Lambda #

triple = lambda x: x * 3

应用 lambda #

print(triple(2))

其它操作 #

Map

l = list(map(triple, [1, 2, 3]))

Filter

l = list(filter(None, [1, 0, 3, False, True]))
l = list(filter(lambda x: x % 2, range(10)))

闭包 #

def select(ele):
    def color(c):
        return '{element} change color {color}'.format(element=ele, color=c)

    return color


print(select('div')('red'))

nonlocal #

内联函数可以访问外部函数的变量,但是无法对其修改,如果需要修改的话则需要声明变量为 nonlocal

def fun1():
    x = 5

    def fun2():
        nonlocal x
        x *= 2  # 尝试修改外部函数中的变量
        return x

    return fun2()


print(fun1())
沪ICP备17055033号-2