即使我知道它已被创建,也无法访问对象?

时间:2012-02-16 13:57:36

标签: python class object

我通过运行文本文件并将单词切成列表来创建类实例,我使用空格作为分割点。

然后我使用这段代码基于数组中的名称创建Word类的对象。

exec("%s = Word(title)" % (title))

我知道正在创建对象,因为我在初始化时打印了对象。

我的问题是,如果我尝试访问这些对象,我会得到:

blue.getWordName()    
NameError: global name 'blue' is not defined

我真的很困惑,并试图寻找答案,但我不确定我使用的是正确的术语。

我已经发现我可以使用字典来实现我的目标,但我真的想更多地理解类实例。

是否有法律禁止从列表项中动态创建类?

我确实试图包含所有代码但它不会让我这样我会包含我认为最相关的代码:

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))

最后我调用已经创建并拼写正确的下面的函数,我还确保'蓝色'肯定在列表中。

blue.getWordName() 

2 个答案:

答案 0 :(得分:6)

不要这样做。 exec是解决此问题的非常糟糕的工具。更好的方法是做到这一点:例如:

words = {}

if count > 0 and wordArray[count - 1] == 'is':
        title = wordArray[count]
        if title not in checkKeyWords():
            words[title] = Word(title)

            if word in verbArray:
                words[title].setWordType('verb')

然后你会做这样的最终检查:

words["blue"].getWordName()

答案 1 :(得分:0)

首先我要说的是,我完全赞同其他答案,而是使用字典。如果您想要解决问题,请使您的示例可重现。稍微改编的代码版本:

class Word():
  def __init__(self, name):
    print 'You have just created me and I\'m called ' + name
    self.name = name
    self.wordType = None
  def setWordType(self, type_string):
    print "Hey, and the method works!"
    self.wordType = type_string

wordArray = ["spam","ni", "is","blue"]
count = 3
if count > 0 and wordArray[count - 1] == 'is':
  title = wordArray[count]
  exec("%s = Word(title)" % (title)) #set class from list item.
  exec("%s.setWordType('verb')" % (title))

工作正常:

> python bla.py 
You have just created me and I'm called blue
Hey, and the method works!

可能是你的缩进搞砸了。您在关键字列表(if title not in checkKeyWords())中检查标题是否为no,并仅在该对象成立​​时创建该对象。可能是您在代码中的某处引用了blue对象,而未创建它。但没有一个可靠的例子,这是不可能的。

相关问题