Creating class instances on the fly

Jason Stokes jstok at
Mon Mar 13 00:52:50 CET 2000

Anthony DeLorenzo wrote in message <8ah975$o24$1 at>...
>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?

Use a dictionary.  Eg,

courses["pys101"] = Course()

>If this isn't possible, is there a way to create instances anonymously,
>perhaps make a list of instance objects or something?

Yes.  Create a list object, and add items using the append or push or
similar methods.

This is a common question by newbies who haven't yet realised that objects
can be stored "anonymously" in container objects, to be retrieved again
according to position, key, priority etc.  I encourage you to learn about
all the container objects: lists, tuples, trees, dictionaries etc. and their

More information about the Python-list mailing list