dinamical object creation

Fred Gansevles gansevle at cs.utwente.nl
Mon May 8 15:56:44 EDT 2000


In article <8f74lo$spt$1 at nnrp1.deja.com>,
  martin_valiente at my-deja.com wrote:
> Hi *
>
> How can I create an object at runtime, giving its module and class
name?
> In java it would be:
>
> Class c = class.forName(stringWithFullNameOfTheClass);
> Object o = c.newInstance();

The simpelest way, without having to figure out which part of the
    "stringWithFullNameOfTheClass"
is the module and which part is the class is to pass them both to a
function, i.e.

    def classFromModule (module, className):
        mod = __import__ (module)
        return getattr (mod, className)

You can use this as follows:

    c = classFromModule (ModuleOfTheClass, NameOfTheClass)
    o = c ()

or, even:

    o = classFromModule (ModuleOfTheClass, NameOfTheClass)()

>
> but, in python I'm a bit lost...
>
> Thanks in advance.
>
> Sent via Deja.com http://www.deja.com/
> Before you buy.
>

--
-----------------------------------------------------------------------
----          Linux/Windows-NT/IntraNetware Administrator          ----
-- Whenever it sounds simple, I've probably missed something! ... Me --
-----------------------------------------------------------------------


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list