python课堂整理13---函数的作用域及匿名函数

name = 'alex'
def foo():
    name = 'jinling'
    def bar():
        print(name)
    return bar
a = foo()
print(a)

阅读上述代码,理解 a 得到的是函数bar 的内存地址,想要运行bar 只需a(),因为bar 函数没有return,所以返回了None

name = 'alex'
def foo():
    name = 'jinling'
    def bar():
        print(name)
    return bar
a = foo()
print(a())

二、同理

def test1():
    print('in the test1')
def test2():
    print('in the test2')
    return test1

res = test2()
print(res)
a = res()
print(a)

三、

def foo():
    name = 'lhf'
    def bar():
        name = 'jinling'
        def tt():
            print(name)
        return tt
    return bar
a = foo()   # 得到bar的内存地址
b = a()     # 运行bar 得到tt的内存地址
c = b()     #运行 tt 打印 Jinling
print(c)    # 得到tt的返回值

上述运行可以用 foo()()() 代替

##########  匿名函数###########

lambda效果等同于以下函数

def cal(x):
    return x + 1

res = cal(10)
print(res)

a = lambda x: x + 1    # x为形参
print(a(10))

 匿名函数不能有复杂的逻辑,只能是一步的过程(一个return的结果)

name = 'alex'
f = lambda x: x + '_sb'
print(f(name))

可以是多个参数

a = lambda x, y, z: (x + 1, y + 1, z + 1)
print(a(1, 2, 3))

匿名函数不应该独立存在,也不应该赋值,而和其他函数连用,以后再写~

猜你喜欢

转载自www.cnblogs.com/dabai123/p/11055454.html
今日推荐