在最后一行中,我收到错误,指出我的对象 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
设置字典的项不会影响包含字典的命名空间。
您可以使用dict[key]
访问字典值:
ants['ant003'].searchFood()
你的意思是使用globals
吗?(不推荐)
...
for name in ants.keys():
globals()[name] = Ant(name) # <----
ant003.searchFood()