Python,循环和闭包 [英] Python, loops and closures

查看:90
本文介绍了Python,循环和闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一位经验丰富的C / C ++(在某种程度上是Java)程序员。我正在学习python,但对这种语言的某些奇怪行为(为我的背景)感到困惑。

I'm a fairly experienced C/C++ (and to some degree, Java) programmer. I'm learning python, but I'm baffled at some strange (for my backgroung) behaviors of the language.

我正在学习嵌套函数和闭包(阅读学习Python,对我来说似乎是一个很好的资料)。

I'm learning about nested function and closures (reading "Learning Python", that seems a really good source for me).

我了解,如果我在调用创建的函数时将def嵌套在for循环中,它将查找捕获的循环变量的最后一个值(因为它是通过引用捕获的,就像C ++程序员会说的那样) )

I understand that if I nest a def inside a for loop when I call the created function, it looks up the last value of the captured loop variable (as it captures by reference, as a C++ programmer would put it)

funcs = []
for i in range(4):
    def f():
        print(i)
    funcs.append(f)

并运行程序的结果是

>>> for f in funcs:
      f()


3
3
3
3

现在,当我偶然发现这个(对我来说似乎是)不一致之处时,我正在全神贯注:如果我这样做

Now, I was wrapping my head around this when I stumbled upon this (what to me seems) an inconsistency: if I do

for i in range(4):
  funcs[i]()


0
1
2
3

如果我愿意的话,会更加困惑/ p>

more baffling, if I do

>>> i = 2
>>> funcs[i]()

2

现在,所有功能列表返回2:

and now, all functions in list returns 2:

for f in funcs:
  f()


2
2
2
2

必须有一些我无法把握的与范围相关的问题

there must be some scope related question that I can't grasp

推荐答案

首先,这将创建四个功能的列表。

First, this creates a list of four functions.

funcs = []
for i in range(4):
  def f():
    print(i)
  funcs.append(f)

每个函数都查找 i 然后打印出来。

Each of these functions looks up the value of i and then prints it.

这会循环遍历函数列表并调用每个函数:

This loops through the list of function and calls each one:

>>> for f in funcs:
      f()

如上所述,这些函数在 i ,现在为3,这是因为i( for range(4)循环较早完成,所以得到四个打印输出为3。

As stated above, these functions look up i, which is 3 right now due to the for i in range(4) loop that completed earlier, so you get four printouts of 3.

现在再次循环,使用 i 作为循环变量:

Now you loop again, using i as the loop variable:

for i in range(4):
  funcs[i]()


0
1
2
3

第一次通过循环, i 为0,因此当函数查找 i 时,它的值为0,然后打印出来。然后将其更改为1,然后更改为2,然后更改为3。

The first time through the loop, i is 0, so when the function looks up i, it gets 0, and then prints that. Then it changes to 1, then 2, then 3.

下面的代码只是用另一种方式更改了 i ,并调用一个函数:

The following code simply changes i in yet another way, and calls a function:

>>> i = 2
>>> funcs[i]()

2

您可以给任何人打电话这些函数,它们仍然会打印2,因为那是现在 i 的值。您只是迷路了,因为您遍历 range(4)创建这些函数,然后遍历 range(4)为函数列表建立索引,然后继续重复使用 i ,然后重新分配 i 并使用

You could've called any of those functions and they still would've printed 2, because that's the value of i now. You're just getting lost because you looped over range(4) to create these functions, then you looped over range(4) to index the list of functions, and you keep reusing i, and then you reassign i and also use it to index the list.

如果要将每个函数的 i 的打印值固定为原值定义函数时,最简单的方法是使用默认参数,因为在定义函数而不是调用函数时将对它们进行评估:

If you want each function's printed value of i to be fixed at what it was when you defined the function, the easiest way to do that is with a default argument, as those are evaluated when the function is defined rather than when it's called:

funcs = []
for i in range(4):
  def f(num=i):
    print(num)
  funcs.append(f)

这篇关于Python,循环和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆