Reputation: 47
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.
Upvotes: 0
Views: 1053
Reputation: 1146
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))
.
Upvotes: 1