dinamical object creation

Rolf Rander Naess rolfn+news at pvv.org
Tue May 9 21:15:04 EDT 2000


[ martin valiente, 08 May 2000 19:31 ]
> 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();

It can be done the same pretty much way in python.  Classes are
separate objects and they are instanciated by calling them as a
function.  Also, all defined symbols are available through hash-tables
(or dictionaries as they are called in python terms).  The global
namespace is accessed through globals(), and the local through
locals().  (See the library reference, section 2.3 for details).

In other words, you can do this:

>>> class foo: pass
... 
>>> classname="foo"
>>> xyzzy = globals()[classname]()
>>> xyzzy
<__main__.foo instance at 80e29b8>
>>> 

or encapsulated in a function:

def createclass(classname, *parameters):
   return apply(globals()[classname], parameters)


Rolf Rander

-- 
                                            (c) 2000 Rolf Rander Næss
http://www.pvv.org/~rolfn/

My mailer limits .sigs to 4 lines. But ingeniously I bypassed this by



More information about the Python-list mailing list