Python class instantiation using name

Bengt Richter bokr at oz.net
Wed Dec 18 20:40:44 EST 2002


On 18 Dec 2002 00:41:49 GMT, bokr at oz.net (Bengt Richter) wrote:

>On Tue, 17 Dec 2002 13:38:06 -0800, Amol P Dharmadhikari <ad at cs.usfca.edu> wrote:
>
>>i.e. something similar to what the below java code snippet can do
>>Object o = java.lang.Class.forName(className).newInstance()
[...]

[Bengt]
> >>> def classForName(name, *args, **kw):
> ...     ns = kw.get('namespace',globals())
> ...     return ns[name](*args)

Bad name choice, sorry. This doesn't do

    java.lang.Class.forName(className)

it does the instance too, i.e., the whole

    java.lang.Class.forName(className).newInstance()

So please s/classForName/classForNameNewInstance/ and reread the example, ok? Sorry.

BTW, while I'm at it, the example

 >>> classForName('FloatType', 123, namespace=types.__dict__)
 123.0

would read cleaner as

 >>> classForName('FloatType', 123, namespace=vars(types))
 123.0

Regards,
Bengt Richter



More information about the Python-list mailing list