擅长:python、mysql、java
<p>只有当变量在当前模块中时,使用全局变量的方法才有效。要在另一个模块中获取值,可以使用getattr:</p>
<pre><code>import other
print getattr(other, "name_of_variable")
</code></pre>
<blockquote>
<p><strong>getattr(object, name[, default])</strong></p>
<p>Return the value of the named attribute of object. name must be a
string. If the string is the name of one of the object’s attributes,
the result is the value of that attribute. For example, getattr(x,
'foobar') is equivalent to x.foobar. If the named attribute does not
exist, default is returned if provided, otherwise AttributeError is
raised.</p>
</blockquote>
<p>比如:</p>
<pre><code>import StackOverflow
number = input("Wich car do you want:")
car = r"Car"+number
print (getattr(StackOverflow, car))
</code></pre>
<p>关于各种“eval”解决方案的注意事项:您应该小心使用eval,特别是当您要评估的字符串来自可能不受信任的源时,否则,如果您得到一个恶意字符串,您可能会最终删除磁盘的全部内容或类似的内容。你知道吗</p>