Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map on methods in Python

I have some classes in Python:

class Class1:
    def method(self):
        return 1
class Class2:
    def method(self):
        return 2

and a list myList whose elements are all either instances of Class1 or Class2. I'd like to create a new list whose elements are the return values of method called on each element of myList. I have tried using a "virtual" base class

class Class0:
    def method(self):
        return 0
class Class1(Class0):
    def method(self):
        return 1
class Class2(Class0):
    def method(self):
        return 2

But if I try map(Class0.method, myList) I just get [0, 0, 0, ...]. I'm a bit new to Python, and I hear that "duck typing" is preferred to actual inheritance, so maybe this is the wrong approach. Of course, I can do

[myList[index].method() for index in xrange(len(myList))]

but I like the brevity of map. Is there a way to still use map for this?

like image 731
Vlad Firoiu Avatar asked Jul 31 '26 14:07

Vlad Firoiu


1 Answers

You can use

map(lambda e: e.method(), myList)

But I think this is better:

[e.method() for e in myList]

 

PS.: I don't think there is ever a need for range(len(collection)).

like image 186
Pavel Anossov Avatar answered Aug 03 '26 04:08

Pavel Anossov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!