lamba的奇怪行为:列表内的getattr(obj,x) [英] strange behavior with lamba: getattr(obj, x) inside a list

查看:90
本文介绍了lamba的奇怪行为:列表内的getattr(obj,x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中:

class A(object):
    pass
    prop1 = 1
    prop2 = 2
    prop3 = 3
    prop4 = 4

obj = A()
tmp = ['prop1', 'prop2', 'prop3', 'prop4']
getter = [ lambda: getattr(obj, x) for x in tmp ]

调用getter时总是得到4:

[getter[i]() for i in range(4)]
#[4, 4, 4, 4]

为什么!?

推荐答案

这是lambda的一个非常普遍的问题.最终,变量x是在调用函数时(而不是在创建函数时)查找的.因此,在循环结束时,x的值是'prop4',所有lambda都将为您提供相同的功能.

This is a very common problem with lambdas. Ultimately, the variable x is looked up when the function is called, not when it is created. As such, at the end of your loop, the value of x is 'prop4' and all your lambdas will give you the same thing.

通常建议的解决方法是在lambda中使用默认参数.创建函数时会对其进行评估.

The commonly proposed fix is to use a default argument in your lambda. It gets evaluated when the function is created.

lambda x=x: getattr(obj,x)

这篇关于lamba的奇怪行为:列表内的getattr(obj,x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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