How to use map () to call class methods in a list of objects

I am trying to call object.method() on a list of objects.

I tried this but cant make it work fine

 newList = map(method, objectList) 

I get a method is not defined error, but I know that this is because it is a class method and not a local function.

Is there a way to do this with map() or a similar inline function? Or should I use a generator / list comprehension?

edit Could you also explain the advantages or differences of your solution from using this list comprehension?

 newList = [object.method() for object in objectList] 
+6
source share
3 answers

newList = map(method, objectList) will call method(object) for each object in the objectlist .

A way to do this using a map would require a lambda function, for example:

 map(lambda obj: obj.method(), objectlist) 

Understanding the list may be a little faster, since you won't need a lambda that has some overhead (discussed a bit here ).

+7
source

Use operator.methodcaller() :

 from operator import methodcaller map(methodcaller('methodname'), object_list) 

This works for any list of objects, all of which have the same method (by name); it doesn't matter if there are different types in the list.

+10
source

If the contents of the list are all instances of the same class, you can prefix the method name with the class name.

 class Fred: def __init__(self, val): self.val = val def frob(self): return self.val freds = [Fred(4), Fred(8), Fred(15)] print map(Fred.frob, freds) 

Result:

 [4, 8, 15] 

This can also be done if the list items are subclasses of the specified class. However, it will still invoke the specified method implementation, even if that method is overridden in a subclass. Example:

 class Fred: def __init__(self, val): self.val = val def frob(self): return self.val class Barney(Fred): def frob(self): return self.val * 2 freds = [Fred(4), Barney(8), Barney(15)] #You might expect the barneys to return twice their val. ex. [4, 16, 30] #but the actual output is [4, 8, 15] print map(Fred.frob, freds) 
+3
source

Source: https://habr.com/ru/post/950838/


All Articles