Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to put constructors in map() function?

Say I have a class, with a constructor that takes an integer. I have a list of integers. How do I use map() to create a list of objects of this class, each constructed with its respective integer?

like image 488
Lucky Avatar asked Aug 13 '12 23:08

Lucky


2 Answers

map(lambda x: MyClass(..., x,...), list_of_ints)

Also consider using list comprehension instead of map:

[MyClass(..., x, ...) for x in list_of_ints]

Either of the above will return a list of objects of your class, assuming MyClass(..., x,...) is your class and list_of_ints is your list of integers.

like image 158
mjgpy3 Avatar answered Sep 20 '22 11:09

mjgpy3


As any other function?

>>> class Num(object):
...     def __init__(self, i):
...             self.i = i
... 
>>> print map(Num, range(10))
[<__main__.Num object at 0x100493450>, <__main__.Num object at 0x100493490>, <__main__.Num object at 0x1004934d0>, <__main__.Num object at 0x100493510>, <__main__.Num object at 0x100493550>, <__main__.Num object at 0x100493590>, <__main__.Num object at 0x1004935d0>, <__main__.Num object at 0x100493610>, <__main__.Num object at 0x100493650>, <__main__.Num object at 0x100493690>]
like image 27
Fedor Gogolev Avatar answered Sep 20 '22 11:09

Fedor Gogolev