Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use map for class method within another class method in Python

I want to define a class method which applies a different class method to a list – I thought the below would work but it doesn’t seem to, am I missing something obvious?

class Foo():

    def __init__(self):
          pass

    def method1(self, data):
        do some stuff

    def method2(self, iterable):
        map(self.method1, iterable)
        do some more stuff

As a concrete example, method2 is applying method1 to each element of a list but the actual content of method1 (printing) doesn’t seem to be executing:

class Foo():
    
    def __init__(self):
        self.factor = 2
        
    def method1(self, num):
        print(num*self.factor)
        
    
    def method2(self, ls):
        map(self.method1, ls)

f = Foo()
f.method2([1,2,3])

I would expect this to print 2, 4, 6 but nothing is printed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

map returns a generator (in Python 3), so you still need to iterate over it:

def method2(self, iterable):
    for val in map(self.method1, iterable):
        do some stuff with val

If you don’t care about the return values, you could always just wrap it in a list: list(map(self.method1, iterable)).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading