<p>在函数的本地命名空间中,<code>exec</code>正在使用import语句,因此这就是定义名称的地方。当函数结束时,这个名称空间就消失了,让您什么都没有。你可能想要的是像<code>exec imp_statement in globals()</code>这样的东西。</p>
<p>为什么不直接用<a href="http://docs.python.org/library/functions.html#__import__" rel="nofollow noreferrer">^{<cd3>}</a>代替字符串咀嚼呢?然后你得到一个模块的参考。然后,您可以在module对象上使用<code>getattr()</code>找出类引用,并将其插入<code>globals()</code>(或者只是将字典传递回调用方,然后调用方可以使用它<code>globals().update()</code>)。</p>
<pre><code>import sys, os
def getClasses(directory):
classes = {}
oldcwd = os.getcwd()
os.chdir(directory) # change working directory so we know import will work
for filename in os.listdir(directory):
if filename.endswith(".py"):
modname = filename[:-3]
classes[modname] = getattr(__import__(modname), modname)
os.setcwd(oldcwd)
return classes
globals().update(getClasses(r"C:\plugin_classes"))
</code></pre>
<p>差不多吧。或者,与其使用模块更新<code>globals()</code>,这可能会破坏您关心的全局变量,不如将类留在字典中,并从那里引用它们:</p>
<pre><code>classes = getClasess(r"C:\plugin_classes")
for clas in classes.itervalues():
instance = clas(1, 2, 3) # instantiate
instance.dosomething_cool(42) # call method
</code></pre>