strange behavior with lamba: getattr(obj, x) inside a list [duplicate]

江枫思渺然 提交于 2019-12-25 07:39:05

问题


In the following example:

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 ]

I am always getting 4 when calling the getter:

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

why!?


回答1:


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.

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)


来源:https://stackoverflow.com/questions/17192226/strange-behavior-with-lamba-getattrobj-x-inside-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!