Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Is it possible to create an instance of a class by giving its name, e.g.:
instance = "TestXYZ"()
Assuming that TestXYZ is imported by a class that imports the code above and TestXYZ is defined as:
class TestXYZ(object): ...
globals()["TestXYZ"]()
Yes, it is possible. The mechanics depend on how you import the class:
>>> globals()["TestXYZ"]() <__main__.TestXYZ object at 0x10f491090>
or
>>> getattr(sys.modules["test_module"], "TestXYZ")() <test_module.TestXYZ object at 0x10cf22090>
Add a comment
You can get a reference to an object from current namespace using:
klass = globals()['TestXYZ']
Then you can create an instance of the class:
instance = klass()
I am not sure why do you want to do this, but instead of using globals() I'd suggest you to create a dictionary here:
globals()
class Foo: pass d = {'Foo':Foo} ins = d['Foo']()
Or move the class to some other module:
import some_module ins = getattr(some_module, 'Foo')()
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
globals()["TestXYZ"](), but why do you want to do this?