Can Python's map function call object member functions?

后端 未结 5 1843
無奈伤痛
無奈伤痛 2021-02-01 14:31

I need to do something that is functionally equivalent to this:

for foo in foos:
    bar = foo.get_bar()
    # Do something with bar

My first i

5条回答
  •  爱一瞬间的悲伤
    2021-02-01 14:53

    This modified code will work:

    for bar in map(lambda f: f.get_bar(), foos):
    # Do something with bar
    

    You provide lambda function here. Simply providing get_bar doesn't work because it is accessible only through an instance of class (f.get_bar()), never by itself.

提交回复
热议问题