I am creating class instances by running a text file and slicing the words into a list, I am using white space as the split point.
I am then creating objects of the class Word based on the names in the array using this bit of code.
exec("%s = Word(title)" % (title))
I know the objects are being created as I have the object print upon initialization.
My problem is that if I try to access these objects I get:
blue.getWordName()
NameError: global name 'blue' is not defined
I am really confused and have tried searching for answers but I’m not sure I am using the correct terminology.
I have figured out that I can use a dictionary to achieve my aim but I really want to understand class instances more.
Is there a law against creating classes on the fly from list items?
I did try to include all of the code but it wouldn’t let me so I’ll include what I think is most relevant:
class Word():
def __init__(self, name):
print 'You have just created me and I\'m called ' + name
self.name = name
if count > 0 and wordArray[count - 1] == 'is':
title = wordArray[count]
if title not in checkKeyWords():
exec("%s = Word(title)" % (title)) #set class from list item.
if word in verbArray:
exec("%s.setWordType('verb')" % (title))
Eventually I call the below function which has been created and is spelled correctly, I have also made sure that ‘blue’ is definitely in the list.
blue.getWordName()
Let me start by saying that I totally agree with the other answer, use dictionaries instead. If you want an answer to your problem, please make your example reproducible. A slightly adapted version of your code:
Works fine:
It might be that you have your indentation messed up. You check that the title is no in a list of keywords (
if title not in checkKeyWords()), and create the object only if that holds. Could be that you refer to theblueobject somewhere in the code, while it was not created. But without a solid example, this is impossible to tell.