Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

Can Python's map function call object member functions?

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 instinct was to use map, but this did not work:

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

Is what I'm trying to accomplish possible with map? Do I need to use a list comprehension instead? What is the most Pythonic idiom for this?

question from:https://stackoverflow.com/questions/7750982/can-pythons-map-function-call-object-member-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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):

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...