python-是否可以创建"def"列表? [英] python - Is it possible to create a list of "def"?
问题描述
我想知道是否可以创建"def"列表,连接20个按钮的列表以及为每个按钮设置不同的回调.
I wonder if it's possible to create a list of "def", to connect a list of 20 buttons, and to have a different callback for each button.
谢谢
推荐答案
def
只是将名称绑定到函数/闭包的常规语句.例如,您可以编写
def
in Python is just a regular statement that binds a name to a function/closure. For example you can write
flist = []
for i in range(30):
def func(x, i=i):
print(x * i)
flist.append(func)
之后,flist[7](6)
将返回42.
棘手的部分只是上述声明中的i=i
.之所以需要这样做,是因为闭包捕获了变量,而不是当前的变量值.没有i=i
,所有功能都将使用与循环相同的变量i
.
The tricky part is only i=i
in the above declaration. This is needed because a closure caputures the variable, not the current variable value. Without that i=i
all of the functions would be using the same variable i
used for looping.
Python还对匿名函数提供了一些支持,因此在上述简单情况下,代码可以缩短为
Python also has some support for anonymous functions so in the above simple case the code could be shortened to
flist = []
for i in range(30):
flist.append(lambda x, i=i: print(x * i))
但是lambda
受限制(只是一个表达式,没有语句)
but lambda
s are very limited (just a single expression, no statements)
这篇关于python-是否可以创建"def"列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!