Can Python's map function call object member functions?

后端 未结 5 1778
無奈伤痛
無奈伤痛 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:38

    Either with lambda:

    for bar in map(lambda foo: foo.get_bar(), foos):
    

    Or simply with instance method reference on your instance's class:

    for bar in map(Foo.get_bar, foos):
    

    As this was added from a comment, I would like to note that this requires the items of foos to be instances of Foo (i.e. all(isinstance(foo, Foo) for foo in foos) must be true) and not only as the other options do instances of classes with a get_bar method. This alone might be reason enough to not include it here.

    Or with methodcaller:

    import operator
    get_bar = operator.methodcaller('get_bar')
    for bar in map(get_bar, foos):
    

    Or with a generator expression:

    for bar in (foo.get_bar() for foo in foos):
    

提交回复
热议问题