I have an array of classes and I want to create objects of them. This works:
classArray = [Auto, Wheel]
objectArray = []
for myClass in classArray:
objectArray += [myClass()]
Can I use the map function to accomplish the same?
objectArray = map( ??? , classArray)
My apologies if this is a dumb question. I am fairly new to Python.
Thanks!
You could use a list comprehension instead. Many consider them to be preferred over the map
function.
objectArrray = [ c() for c in classArray ]
If you insist on using map
, you can do
map(lambda c: c(), classArray)
Here, I am creating an anonymous function with lambda
that simply takes the item, and calls it. If you are unfamiliar with map
, it takes a 1-parameter function as the first argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With