<p>我是一个python/编程新手,也许我的问题毫无意义。</p>
<p>我的问题是,如果一个变量是动态的,我不能让它成为全局变量,我的意思是我可以这样做:</p>
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(BrokenCristals)
def accesingShotInstance():
import movieClass
return BrokenCristals.get_name()#it returns me 'BrokenCristals'
</code></pre>
<p>但是如果我声明一个字符串变量而不是这样做:</p>
<pre><code>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'
</code></pre>
<p>我试过这个:</p>
<pre><code>global vars()[a]
</code></pre>
<p>而这个:</p>
<pre><code>global eval(a)
</code></pre>
<p>但这给了我一个错误。我该怎么办?</p>