我是一个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)
但它给了我一个错误。我该怎么办?
答案 0 :(得分:10)
为了完整起见,这是您原始问题的答案。但这几乎肯定不是你想要做的事情 - 很少有情况下修改范围的dict
是正确的。
globals()[a] = 'whatever'
答案 1 :(得分:7)
使用dict:
而不是动态全局变量movies = {}
a = 'BrokenCristals'
movies[a] = movieClass.shot()
movies[a].set_name(a)
# etc
答案 2 :(得分:1)
global关键字指定您在一个范围内使用的变量实际上属于外部范围。由于您的示例中没有嵌套作用域,因此global不知道您要执行的操作。见Using global variables in a function other than the one that created them
答案 3 :(得分:0)
第一个语法错误没有方括号:
File "main.py", line 6
global BrokenCristals
^
SyntaxError: name 'BrokenCristals' is assigned to before global declaration
第二个语法错误 global 末尾没有字母 s:
File "main.py", line 6
global [BrokenCristals]
^
SyntaxError: invalid syntax
def creatingShotInstance():
import movieClass
BrokenCristals = movieClass.shot()
globals [BrokenCristals]
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()
def creatingShotInstance():
import movieClass
a = 'BrokenCristals'
vars()[a] = movieClass.shot()
globals [a]
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()