Skip to content

Commit cbacd3e

Browse files
author
暮晨
committed
EX.The sticky output function
1 parent 48f78ef commit cbacd3e

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

README.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ So, here we go...
3333
- [> Evaluation time discrepancy/评估时间差异](#-evaluation-time-discrepancy评估时间差异)
3434
- [> `is` is not what it is!/出人意料的`is`!](#-is-is-not-what-it-is出人意料的is)
3535
- [> A tic-tac-toe where X wins in the first attempt!/一蹴即至!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt一蹴即至)
36-
- [> The sticky output function](#-the-sticky-output-function)
36+
- [> The sticky output function/麻烦的输出](#-the-sticky-output-function麻烦的输出)
3737
- [> `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-)
3838
- [> The surprising comma](#-the-surprising-comma)
3939
- [> Backslashes at the end of string](#-backslashes-at-the-end-of-string)
@@ -549,7 +549,7 @@ board = [row]*3
549549
550550
---
551551
552-
### > The sticky output function
552+
### > The sticky output function/麻烦的输出
553553
554554
```py
555555
funcs = []
@@ -570,21 +570,22 @@ funcs_results = [func() for func in funcs]
570570
>>> funcs_results
571571
[6, 6, 6, 6, 6, 6, 6]
572572
```
573-
Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.
574573
575-
//OR
574+
即使每次在迭代中将 `some_func` 加入 `funcs` 前的 `x` 值都不相同, 所有的函数还是都返回6.
575+
576+
// 再换个例子
576577
577578
```py
578579
>>> powers_of_x = [lambda x: x**i for i in range(10)]
579580
>>> [f(2) for f in powers_of_x]
580581
[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]
581582
```
582583
583-
#### 💡 Explanation
584+
#### 💡 说明:
584585
585-
- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.
586+
- 当在循环内部定义一个函数时, 如果该函数在其主体中使用了循环变量, 则闭包函数将与循环变量绑定, 而不是它的值. 因此, 所有的函数都是使用最后分配给变量的值来进行计算的.
586587
587-
- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.
588+
- 可以通过将循环变量作为命名变量传递给函数来获得预期的结果. **为什么这样可行?** 因为这会在函数内再次定义一个局部变量.
588589
589590
```py
590591
funcs = []

0 commit comments

Comments
 (0)