reflection as in Java: how to create an instance from a classname
qgallet at gmail.com
Mon Jan 5 17:37:21 CET 2009
On Mon, Jan 5, 2009 at 5:34 PM, Bruno Desthuilliers
<bruno.42.desthuilliers at websiteburo.invalid> wrote:
> guss a écrit :
>> I cannot find a satisfying answer to this question on the web so let's
>> try here.
>> My problem is the following, I would like to instantiate some object
>> from a configuration file that would contain class names like for
>> example classname=org.common.resource.MyResource.
>> Here my resource is the class to instanciate and it is in the module
>> resource that is in a package hierachy.
>> In fact I would like to do something very similar to the Java:
>> klass = Class.forname("org.common.resource.MyResource")
>> instance = klass.newInstance()
>> The second line is easy once I have a classobj but I have some
>> problems to find the right recipe for getting it.
>> I know how to create a class from scratch with new.classobj but how do
>> you get a class object and then create an object ?
>> I would like a recipe working for all cases (whatever the module is
>> not the local one ...)
> use __import__ to get the module object, then getattr(module, classname) to
> get the class object (sorry, no much time right now to give you a full
> recipe, but that should be enough to get you started).
A longer version of Bruno's idea can be found here :
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list