gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:41:46 24 4
gpt4 key购买 nike

我是一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com