【坚持】Selenium+Python学习之从读懂代码开始 DAY5

2018/05/22

函数作为返回值

[来源:廖雪峰的官方网站](https://www.liaoxuefeng.com/

#No.1


def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:
            ax = ax + n
        return ax
    return sum

f = lazy_sum(1, 3, 5, 7, 9)
print(f)

x = f()
print(x)
resut:
d:\fly\Python (master -> origin)
λ python test.py
<function lazy_sum.<locals>.sum at 0x0000014CE4C5C9D8>
25

闭包

[讲解很清晰的视频教程:Python开发+人工智能实战课程(基础篇)-【马哥教育】](https://ke.qq.com/course/143162

#No.2


def f1(x):
    def f2(y):
        return y ** x
    return f2

a = f1(3)
b = a(2)
c = a(3)

print(b, c)

外层环境(f1),内层函数(f2)
f1为f2提供运行环境
resut:
d:\fly\Python (master -> origin)
λ python test.py
8 27

猜你喜欢

转载自www.cnblogs.com/flyin9/p/9070285.html