<p>我有一个名为<code>dynamic_cls_ex.py</code>的模块和两个名为<code>FooButton</code>和<code>BarButton</code>的类。我使用下面的代码从字符串中动态实例化我感兴趣的类。在</p>
<p><strong>问题:</strong>我使用<code>__import__</code>导入模块,这会导致<code>main</code>运行两次。<em>这是我的基本理解。请随时给我一个更好的解释</p>
<pre><code># !/usr/bin/python
class FooButton(object):
def __init__(self):
print 'I am a foo button'
class BarButton(object):
def __init__(self):
print 'I am a bar button'
method = 'Foo'
class_name = '%sButton' % method
module = __import__('dynamic_cls_ex')
Button = getattr(module, class_name)
Button()
# OUTPUT:
# >> I am a foo button
# >> I am a foo button
</code></pre>
<p><strong>如何在不需要导入当前运行的模块的情况下动态实例化一个类?</strong></p>