我试图让我的绘图程序的用户(用 pygame 用 python 编写)重命名选定的对象,然后能够通过实时解释器通过它们的名称访问它们。以下是所有可绘制对象的基类的方法。运行此代码时,我没有收到任何错误,但是当我尝试通过其新名称访问对象时,我被告知未定义具有该名称的变量。任何想法为什么会这样?
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