Python Forum
Create class instances from list of strings - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Create class instances from list of strings (/thread-5094.html)



Create class instances from list of strings - pythonck - Sep-18-2017

I have a list of strings as follows: somewords = ['apple', 'orange', 'pear']
I want to be able to have attributes for these words.
So I create a class as follows:

class Word():
...def __init__(self):
......self.size = ""
......self.color = ""
......self.fresh = bool
......self.age = int

and I would like to create instances of the class Word from my list like this:

apple = Word()
apple.size = 'big'
apple.color = 'red'
apple.fresh = True
apple.ageindays = 3

orange = Word()
orange.size = 'small'
orange.color = 'yellow'
orange.fresh = False
orange.ageindays = 10

If I could convert the strings in the list to variables I could simply iterate across the list to create the instances of the Word class. But I don't think this can be done or is there some other way to create instances of class from a list of strings?









o


RE: Create class instances from list of strings - ichabod801 - Sep-18-2017

I would put them in a dictionary:

words = {word': Word() for word in somewords}
Getting the attributes in is another question, but you could probably make them parameters to __init__, and then load them in while creating the dict.