在python中声明一个全局动态变量

use*_*457 4 python

我是一个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'
Run Code Online (Sandbox Code Playgroud)

但如果不这样做,我声明一个像这样的字符串变量:

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'
Run Code Online (Sandbox Code Playgroud)

我试过这个:

global vars()[a]
Run Code Online (Sandbox Code Playgroud)

还有这个:

global eval(a)
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误.我该怎么办?

Kat*_*iel 11

为了完整起见,这是您原始问题的答案.但这几乎肯定不是你想要做的事情 - 很少有情况下修改范围dict是正确的.

globals()[a] = 'whatever'
Run Code Online (Sandbox Code Playgroud)


Ned*_*der 7

使用dict而不是动态全局变量:

movies = {}

a = 'BrokenCristals'

movies[a] = movieClass.shot()
movies[a].set_name(a)
# etc
Run Code Online (Sandbox Code Playgroud)