2

I would like to map a method over a list of objects instantiating different classes. All the objects inherit from the same base class and define a method of the desired name.

To make it clearer consider the following code:

class A:
    def __init__(self, x):
        self.x = x

    def foo (self):
        return self.x

class B(A):
    def foo (self):
        return self.x+1

class C(A):
    def foo (self):
        return self.x-1

Now consider a list of objects instantiating the classes B and C. I would like to do something like that:

result = []
for obj in [B(1), C(1)]:
    result.append(obj.foo())

How would you proceed to map the method foo on each element of the list? Is it at all possible? The best I could come up with is something like that:

map(A.foo, [B(1), C(1)])

but clearly it doesn't return my desired result. How can I specify the method related to the object?

I hope I made myself clear.

NB: I work primarily with Python2.7, but I would equally be interested in solutions valid for "newer" versions.

4

3 に答える 3

4

Map(A.foo, [B(1), C(1)]) is basically doing A.foo(B(1)) and A.foo(C(1)) which isn't what you are looking for.

Using your classes from above, I would just do:

In: objs = [B(1), C(1)]
In: [x.foo() for x in objs]
Out: [2, 0]

Amjith has a pure map implementation if you'd prefer that.

于 2012-04-19T15:32:26.743 に答える
3
>>> map(lambda x: x.foo(), [B(1), C(1)])
>>> [2, 0]

The lambda function will take each object in the list and call foo() on that object. Thus the resulting list will have the results returned by the corresponding object's foo().

于 2012-04-19T15:29:12.740 に答える
3

For most practical purposes, I'd recommend @AlG's list comprehension, but you can do this with map as well:

>>> import operator
>>> map(operator.methodcaller("foo"), [B(1), C(1)])
[2, 0]
于 2012-04-19T15:34:59.270 に答える