Reputation: 4574
Can I somehow refer to a method without using the lambda
keyword?
Say we have following example code:
class AbstractDummy:
def size(self):
raise NotImplementedError
class Dummy1(AbstractDummy):
def size(self):
return 10
class Dummy2(AbstractDummy):
def size(self):
return 20
If I have my example objects:
dummies1 = [Dummy1(), Dummy1(), Dummy1()]
dummies2 = [Dummy2(), Dummy2()]
Then if I want to map
them, and I can do that with extracted function parameter to save me some characters:
f = lambda x : x.size()
map(f, dummies1)
map(f, dummies2)
Question here: can I somehow avoid this temporary f
and/or lambda
keyword?
To make a small comparison, in Java it would be possible to refer to AbstractDummy::size
and so the invocation would look a bit like print(map(AbstractDummy::size, dummies1)
.
Upvotes: 1
Views: 239
Reputation: 7806
In this case you would probably want to use a list comprehension
[x.size() for x in dummies1]
[x.size() for x in dummies2]
Upvotes: 4
Reputation: 531948
The operator
module provides methodcaller
for this.
from operator import methodcaller
f = methodcaller('size')
results1 = [f(x) for x in dummies1]
results2 = [f(x) for x in dummies2]
though [x.size() for x in ...]
is simpler, as in C_Z_'s answer. methodcaller
is useful for when you need a function as a function argument, for example
# Sort some_list_of_objects on return value of each object's `a` method.
sorted_list = sorted(some_list_of_objects, key=methodcaller('a'))
Upvotes: 4