我是一名Python/编程新手,也许我的问题根本没有意义。
我的问题是如果变量是动态的,我无法将其设置为全局变量,我的意思是我可以这样做:
def creatingShotInstance():
import movieClass
BrokenCristals = movieClass.shot()
global BrokenCristals #here I declare BrokenCristals like a global variable and it works, I have access to this variable (that is a shot class instance) from any part of my script.
BrokenCristals.set_name('BrokenCristals')
BrokenCristals.set_description('Both characters goes through a big glass\nand break it')
BrokenCristals.set_length(500)
Fight._shots.append(BrokenCristals)
def accesingShotInstance():
import movieClass
return BrokenCristals.get_name()#it returns me 'BrokenCristals'
但是,如果我声明一个字符串变量,像这样:
def creatingShotInstance():
import movieClass
a = 'BrokenCristals'
vars()[a] = movieClass.shot()
global a #this line is the only line that is not working now, I do not have acces to BrokenCristals class instance from other method, but I do have in the same method.
eval(a+".set_name('"+a+"')")
eval(a+".set_description('Both characters goes through a big glass\nand break it')")
eval(a+".set_length(500)")
Fight._shots.append(vars()[a])
def accesingShotInstance():
import movieClass
return BrokenCristals.get_name()#it returns me 'BrokenCristals is not defined'
我尝试了这个:
global vars()[a]
并且这个:
global eval(a)
但是它给我一个错误。我该怎么办?
global a
处理名为 'a' 的全局变量;如果你知道我是什么意思(不是全局是一个函数 -global(a)
不会起作用),则global a
变成了global('a')
。 - Chris Morganvars()
返回的字典。 - martineau