Creating class instance from module and class name

Chris Rebert clp2 at rebertia.com
Tue Oct 6 03:30:19 EDT 2009


On Tue, Oct 6, 2009 at 12:09 AM, gentlestone <tibor.beck at hotmail.com> wrote:
> On 6. Okt, 08:55 h., Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
>> On Mon, 05 Oct 2009 23:32:27 -0700, gentlestone wrote:
>> > Suppose I've saved the class name and (don't know how) I've also saved
>> > the Class's module (package path or I don't know what's the name for XYZ
>> > "from X.Y.Z import ...). How can I construct a new class according to
>> > saved informations? If I don't know what Class it could be, only I have
>> > the saved Class name?
>>
>> If you have the module *object*, and the name of the class, then you can
>> do this:
>>
>> theclass = getattr(module, "MyClass")
>>
>> to get the class itself, and then call it as normal to instantiate it:
>>
>> instance = theclass(args)
>>
>> Classes are just like any other object in that regard.
>>
>> If you have the *name* of the module, you can import it first to get the
>> module object:
>>
>> module = __import__('module_name')
>> theclass = getattr(module, "MyClass")
>> instance = theclass(args)
>>
>> There may be some complications if you have a dotted package name, in
>> which case the docs for __import__ are your friend :)
>>
>> --
>> Steven
>
> thx for help
>
> one more question - __class__ is the way for getting the classname
> from the class instance -

No, that'd be some_instance.__class__.__name__

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list