I have the need to take a string argument and create an object of the class named in that string in Python. In Java, I would use Class.forName().newInstance(). Is there an equivalent in Python?
Thanks for the responses. To answer those who want to know what I’m doing: I want to use a command line argument as the class name, and instantiate it. I’m actually programming in Jython and instantiating Java classes, hence the Java-ness of the question. getattr() works great. Thanks much.
Reflection in python is a lot easier and far more flexible than it is in Java.
I recommend reading this tutorial (on archive.org)
There’s no direct function (that I know of) which takes a fully qualified class name and returns the class, however you have all the pieces needed to build that, and you can connect them together.
One bit of advice though: don’t try to program in Java style when you’re in python.
If you can explain what is it that you’re trying to do, maybe we can help you find a more pythonic way of doing it.
Here’s a function that does what you want:
You can use the return value of this function as if it were the class itself.
Here’s a usage example:
How does that work?
We’re using
__import__to import the module that holds the class, which required that we first extract the module name from the fully qualified name. Then we import the module:In this case,
mwill only refer to the top level module,For example, if your class lives in
foo.bazmodule, thenmwill be the modulefooWe can easily obtain a reference to
foo.bazusinggetattr( m, 'baz' )To get from the top level module to the class, have to recursively use
gettatron the parts of the class nameSay for example, if you class name is
foo.baz.bar.Modelthen we do this:This is what’s happening in this loop:
At the end of the loop,
mwill be a reference to the class. This means thatmis actually the class itslef, you can do for instance: