Defining Multiple Objects at Once

Peter Abel PeterAbel at gmx.net
Wed May 26 18:44:34 EDT 2004


"SilverShadow" <GPodubs at hotmail.com> wrote in message news:<464afbb13c2bd25bb14351db772159e0 at localhost.talkaboutprogramming.com>...
> Hello,
> 
> I'm having trouble with something that may be easily remedied.  I use
> Cantera running on Python.  I need to make multiple "Reactor()" objects
> and have them assigned a different (user defined) name.  For example:
> 
> reactors = [R1, R2, R3...etc.]
> for reac in reactors:
>      reac = Reactor()
> 
> My problem is there is no way to operate on each reactor separately. 
> (e.g.  R1.temperature())  The only thing that can be done is
> reac.temperature(), but that gets overwritten each time.  So, my question
> is, is there any way to assign multiple names w/o having to write out
> lines of explicit definitions in the code?  Thank you in advance.

Most of time one wants to put the instances in a definite namespace.
And in pyhton namespace handling is mostly organized by dictionaries.
So it's not necessary to declare an additional dictionary while the
namespace dictionary already exists.
And most of time the target namespace is the global namespace.

The following example will show, how to instantiate a bunch of 
variables for the global namespace:

>>> # An example Reactor class, to show different instances
>>> class Reactor:
... 	number_of_instances=0
... 	def __init__(self):
... 		Reactor.number_of_instances+=1
... 		self.Reactor_Number=Reactor.number_of_instances
... 	def show(self):
... 		print 'Reactorname: Reactor#%d' % self.Reactor_Number
... 
>>> #  A list of variablenames for Reactor-instances
>>> #  its a lazy declaration, cause I dont want to write commas
>>> #  and single quotmarks
>>> reactor_name_list='R1 R2 R3 R4 R5'.split()
>>> reactor_name_list
['R1', 'R2', 'R3', 'R4', 'R5']
>>> # Add the instances with the declared names to the global
>>> # namespace (it could be any else) which is represented by
globals()
>>> reduce(lambda last,name:globals().__setitem__(name,Reactor()),reactor_name_list,0)
>>> # I took reduce rather than map, cause it doesnt create a list,
>>> # which will be thrown away
>>> # Remark the startvalue "0", cause otherwise "R1" wouldnt be
instantiated
>>> R1
<__main__.Reactor instance at 0x00DFC9D8>
>>> R1.show()
Reactorname: Reactor#1
>>> R2.show()
Reactorname: Reactor#2
>>> # etc.
>>> R5.number_of_instances
5
>>> R5.show()
Reactorname: Reactor#5
>>> 

Hope I could help you.

Regards
Peter



More information about the Python-list mailing list