Convert list of strings into objects

Captain_Panda picture Captain_Panda · Dec 29, 2014 · Viewed 13.6k times · Source

I have a list of strings, say something like:

listofstuff = ['string1', 'string2', 'string3', ...]

I have a created a custom class object for what I want to do. All I want now is to create a bunch of said objects that are named the strings in my list. How can I do this?

So I have something like:

for object in listofstuff:
     object = classthing(inputs)

But it doesn't work. How do I do this?

EDIT: Maybe I should clarify. I have an input file that can change, and in said input file is a list of names. I want to create a bunch of class objects that are all called the names in the list.

So someone gives me a list like stuff = ['car1', 'car2', 'car3'] and I now want to create a bunch of new Car objects, each one called car1, car2, etc. So that later I can do things like car1.calculate_price() or whatever.

EDIT 2: Sorry for all the edits, but I also wanted to share something. In what I am trying to do, objects are grouped together in specific ways, but ways that aren't obvious to the user. So it would be like 'car1_car23_car4'. So I wanted, if I asked the user, which car do you want to pick? And they chose car4, it would create an object instead named car1_car23_car4, instead of car4.

Answer

user2555451 picture user2555451 · Dec 29, 2014

Creating names dynamically is not the right approach. It is very easy to loose track of them, to make more or less than you need, or to accidentally overwrite an existing name.

A better approach would be to make a dictionary where the keys are your strings from listofstrings and the values are instances of your class. You can use a dict comprehension and write something like:

dct = {name: classthing(inputs) for name in listofstuff}

Below is a demonstration1 of what this does:

>>> class classthing: # This represents your class
...     def __init__(self, name):
...         self.name = name
...
>>> listofstuff = ['Joe', 'Bob', 'Mary']
>>>
>>> dct = {name: classthing(name) for name in listofstuff}
>>> dct  # dct now holds all the data you need
{'Mary': <__main__.classthing object at 0x0205A6D0>, 'Joe': <__main__.classthing object at 0x0205A690>, 'Bob': <__main__.classthing object at 0x0205A6B0>}
>>>
>>> # Each value in dct is an individual instance of your class
>>> dct['Joe'].name
'Joe'
>>> dct['Bob'].name
'Bob'
>>> dct['Mary'].name
'Mary'
>>>

1For the sake of the demonstration, I replaced inputs with name. You do not have to do this in your real code though.