Python闭包和单元格(闭包值) [英] Python closures and cells (closed-over values)
本文介绍了Python闭包和单元格(闭包值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是Python机制,使
What is the Python mechanism that makes it so that
[lambda: x for x in range(5)][2]()
是4?
将x的副本绑定到每个lamba表达式的常见技巧是使上述表达式等于2?
What is the usual trick for binding a copy of x to each lamba expression so that the above expression will equal 2?
我的最终解决方案:
for template, model in zip(model_templates, model_classes):
def create_known_parameters(known_parms):
return lambda self: [getattr(self, p.name)
for p in known_parms]
model.known_parameters = create_known_parameters(template.known_parms)
推荐答案
我通常使用 functools.partial
[ partial(lambda x: x, x) for x in range(5) ]
或者,您自己可以:
[ (lambda x: (lambda: x))(x) for x in range(5) ]
这篇关于Python闭包和单元格(闭包值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文