I have a module named dynamic_cls_ex.py
and two classes named FooButton
and BarButton
. I am using the below code to dynamically instantiate the class I am interested in from a string.
The problem: I'm using __import__
to import the module, which causes main
to run twice. this is my elementary understanding. Please feel free to give me a better explanation on what's actually going on
# !/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
How can I dynamically instantiate a class without needing to import the module I'm currently running?