Can you create a class from a string name

Lenard Lindstrom len-l. at telus.net
Sat Mar 1 19:23:46 EST 2003


"Vivek Sawant" <vivek-sawant at verizon.net> wrote in message
news:3E611ABE.2050102 at verizon.net...
> Hi,
>
> is there a way to create a class object or an instance object for a
> class if you have the name of the class as a string at the runtime.
>

You can use Python's dynamic execution features to do what you want. To
retrieve a reference to an existing class object use the built-in 'eval'
function.

classobj = eval('<classname>')

Create an instance of the class by calling the returned object.

classinstance = classobj(<constructor args>)

To define an entirely new class at run-time use the 'exec' statement. The
following example creates a minimal class, but the definition can be as
complicated as you need.

# Class name is defined by a string.
classname = 'mynewclass'

# The class definition is also a string. The '%s' will be replaced by the
class name later.
# When writing a compound statement as a string make sure the indentation
method
# is consistent, e.g. four spaces. See section 2.4.1 in Python Language
Manual
# for more on triple-quoted strings.
definition = """class %s:
    pass
"""

# Execute the class definition statement. Insert the class name using a
# string formatting command '%' (section 2.2.6.2 in Python Library
Reference).
exec definition % classname

# Create an instance of the class.
newinstance = eval(classname)()

# This also works, but only when classname == 'mynewclass'.
newinstance = mynewclass()

> For example, in Java you can create a 'Class' object as:
>
> Class.forname ('<classname>')
>
> Thanks.
>
> \vivek
>

The Java Class.forName method returns a reference to an already existing
'Class' object. It does not create a new 'Class' object. It will not create
a new class at run time.

I hope this helps.

Lenard Lindstrom









More information about the Python-list mailing list