2
我试图让我的绘图程序(用python写pygame)的用户重命名所选对象,然后能够通过他们的名字通过实时解释器访问它们。以下是所有可绘制对象的基类的一种方法。当这段代码运行时,我没有得到任何错误,但是当我尝试通过它的新名称访问对象时,我被告知具有该名称的变量没有被定义。 任何想法,为什么这可能是?使用eval在全局范围创建新变量
def rename(self,newName):
"""
Gives this drawable a new name by which the user my reference it in
code
"""
#Create a new variable in the global scope
command = 'global ' + newName + '\n'
#Tie it to me
command += newName + ' = self' + '\n'
#If I already had a name, I'll remove this reference
if self.name != None:
command += 'del ' + self.name
#Execute the command
exec(command)
#Make this adjustment internally
self.name = newName
这似乎是为我工作。感谢你的帮助,rodrigo! – hedgehogrider
虽然,我仍然不明白exec为什么不起作用。它不能与exec(command,globals())一起工作。任何文献,我可以阅读这个? – hedgehogrider
嗯,经过一些测试,看起来我错了'exec'使用另一个'globals'。其实,一些简单的例子对我来说很有效......但是,我觉得在删除之前你并没有添加''global'+ self.name',它并没有失败,所以我猜测你是在删除插入之后立即使用相同的名称! – rodrigo