Creating class instances on the fly

Daniel Berlin dan at cgsoftware.com
Sun Mar 12 19:07:40 EST 2000


gonzo at vex.net (Anthony DeLorenzo) writes:

Check out the new module, it does what you want.
Alternatively, you should be able to do this with exec, like so:

bash-2.03# python
Python 1.5.2 (#5, Mar 12 2000, 18:58:56)  [GCC 2.95.2 19991024 (release)] on freebsd4
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> class Course:
...     pass
...
>>> value='phys101'
>>> exec(value+"=Course()")
>>> dir()
['Course', '__builtins__', '__doc__', '__name__', 'phys101', 'value']
>>>
>>> print type(phys101)
<type 'instance'>
>>> print phys101
<__main__.Course instance at 80fed00>
>>>

> 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




More information about the Python-list mailing list