Creating class instances on the fly

Gerald Klix gklix at hassler.de
Tue Mar 14 22:21:11 CET 2000


Anthony DeLorenzo wrote:

> I'm doing some XML parsing, andI'd like to be able to add the values
> to class instances.  Is there any way to create an instance of a class
> with a dynamically assigned name?
>
> class Course:
>         pass
>
> value = 'phys101'
>
> For example....  How could I do the equivalent of this?
>
> phys101 = Course()
>
> for each course name, withhout knowing them ahead of time?
>
> If this isn't possible, is there a way to create instances anonymously,
> perhaps make a list of instance objects or something?
>
> Thanks,
>
> Tony
>
> --
> # Anthony DeLorenzo <drgonzo at canada.com>
> # http://www.vex.net/~gonzo/
> # mojo wire: 209-391-8932

It's not quite clear what you want to do.

If you want to create instances of class with a parametric name you can do
the following:

def createClass( name ):
    class Dummy:
        pass
    answer = Dummy()
    answer.__class__.__name__ = name
    return answer

if you want a list of instances you simply can get it with code like this:

map( createClass, [ "foo", "bar", "and", "the", "like" ] )

CU
Gerald





More information about the Python-list mailing list