在python中声明全局动态变量

2024-05-16 05:31:30 发布

您现在位置: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'

但是如果我声明一个字符串变量而不是这样做:

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)

但这给了我一个错误。我该怎么办?


Tags: nameimportisdefhaveevalnotit
4条回答

为了完整起见,这里是你最初问题的答案。但几乎可以肯定的是,这并不是您想要做的——在极少数情况下,修改作用域的dict是正确的。

globals()[a] = 'whatever'

global关键字指定您在一个作用域中使用的变量实际上属于外部作用域。由于您的示例中没有嵌套作用域,因此global不知道您要做什么。见Using global variables in a function other than the one that created them

使用dict代替动态全局变量:

movies = {}

a = 'BrokenCristals'

movies[a] = movieClass.shot()
movies[a].set_name(a)
# etc

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

movies = {}

a = 'BrokenCristals'

movies[a] = movieClass.shot()
movies[a].set_name(a)
# etc

相关问题 更多 >