Python Forum

Full Version: Create class instances from list of strings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.