简体   繁体   English

如何使用map()在对象列表上调用类方法

[英]How to use map() to call class methods on a list of objects

I am trying to call object.method() on a list of objects. 我试图在对象列表上调用object.method()

I have tried this but can't get it to work properly 我试过这个,但无法让它正常工作

newList = map(method, objectList)

I get the error method is not defined but I know that is because it is a class method and not a local function. 我得到的错误method is not defined但我知道这是因为它是一个类方法而不是本地函数。

Is there a way to do this with map() , or a similar built in function? 有没有办法用map()或类似的内置函数来做到这一点? Or will I have to use a generator/list comprehension? 或者我必须使用生成器/列表理解?

edit Could you also explain the advantages or contrast your solution to using this list comprehension? 编辑您是否也可以解释使用此列表理解的优势或对比您的解决方案?

newList = [object.method() for object in objectList]

Use operator.methodcaller() : 使用operator.methodcaller()

from operator import methodcaller

map(methodcaller('methodname'), object_list)

This works for any list of objects that all have the same method (by name); 这适用于所有具有相同方法的对象列表(按名称); it doesn't matter if there are different types in the list. 如果列表中有不同的类型则无关紧要。

newList = map(method, objectList) would call method(object) on each object in objectlist . newList = map(method, objectList)将在objectlist每个object上调用method(object)

The way to do this with map would require a lambda function, eg: 使用map执行此操作的方法需要lambda函数,例如:

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

A list comprehension might be marginally faster, seeing as you wouldn't need a lambda, which has some overhead (discussed a bit here ). 列表理解可能会略微加快,因为你不需要一个lambda,它有一些开销(在这里讨论一下)。

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 elements of the list are subclasses of the specified class. 如果列表的元素是指定类的子类,也可以这样做。 However, it will still call the specified implementation of the method, even if that method is overridden in the 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM