Python:类对象是实例化的,但没有定义?

时间:2014-01-01 08:01:01

标签: python oop global-variables instance

在最后一行中,我得到了我的对象ant003未定义的错误。但为什么呢?

class Ant:

    def __init__(self, name):
        """Initializes the data."""
        self.name = name
        self.food = 0
        self.posx = 0
        self.posy = 0
        print("(Initializing {0})".format(self.name))

    def searchFood(self):
        self.food = self.food + 1
        print("Ant {1} has {0} food.".format(self.food, self.name))


ant001 = Ant("Anton")
ant001.searchFood()
ant002 = Ant("Bob")

ants = {'ant003': None, 'ant004': None}
for name in ants.keys():
    ants[name] = Ant(name)
    print ants[name]

#print ant001
#print ant003

ant003.searchFood()   # NameError: name 'ant003' is not defined

1 个答案:

答案 0 :(得分:4)

设置字典项不会影响包含字典的命名空间。

您可以使用dict[key]访问字典值:

ants['ant003'].searchFood()

您的意思是使用globals吗? (不推荐)

...
for name in ants.keys():
    globals()[name] = Ant(name) # <----

ant003.searchFood()