Created
April 23, 2020 02:01
-
-
Save mildcore/69b1287f80bb12daf24b71eeb6bd8f26 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# closure_lambda_lazy | |
Closure: | |
内部函数引用的是外部函数的参数或变量,但是引用的是变量的最终值(外部函数的那次生命周期,外部函数可跨层级) | |
内层函数作为值返回时不会直接运算,等调用它的时候才会运算 | |
看几个例子 | |
# 1.Lazy, 另外内部函数引用了外部函数的参数,且外部函数生命周期已经结束不影响其使用. | |
>>> lazy_square_print = lambda i: lambda: print(i**2) | |
>>> square_print = lazy_square_print(5) | |
>>> square_print() | |
25 | |
# 2.引用的是外部函数变量的最终值 | |
# not 0, 1, 4, but 4, 4, 4 | |
>>> lazy_squares = lambda: [lambda: i**2 for i in range(3)] | |
>>> for sq_fun in lazy_squares(): | |
print(sq_fun()) | |
4 | |
4 | |
4 | |
# 3.跨级引用外部函数变量,效果同2. 即便第二层函数当时已经调用,第三层函数引用的依然是最外层函数的i | |
>>> lazy_squares = lambda: [(lambda: lambda: i**2)() for i in range(3)] | |
>>> for sq_fun in lazy_squares(): | |
print(sq_fun()) | |
4 | |
4 | |
4 | |
# 4.第二层函数可以定义自己的参数,第一层的变量作为值传入第二层; | |
# 这样的话,第三层引用的实际是第二层的参数,而不是第一层; 这应是python变量解析顺序的预期结果. | |
>>> lazy_squares = lambda: [(lambda i: lambda: i**2)(i) for i in range(3)] | |
>>> for sq_fun in lazy_squares(): | |
print(sq_fun()) | |
0 | |
1 | |
4 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment