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

标签 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)

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

最佳答案

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

globals()[a] = 'whatever'

关于python - 在python中声明一个全局动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277056/

相关文章:

python - 使用全局变量作为默认参数

python - 计算 numpy 数组的平均值

python - Pygame 碰撞检查错误

python - hash(time.time()) 总是唯一的

python - 从 python 中的嵌套 URL 中抓取并解析表

python - 如何正确压缩此 Python IF 语句?

python - 将条目添加到现有 XMLFile Python

Python:列表到 JSON

python - 在使用 django-admin.py 或 manage.py 时存在差异

python - Django 找不到 psycopg2 模块