using names before they're defined

Patrick Maupin pmaupin at gmail.com
Sat Jul 22 20:08:35 EDT 2006


davehowey at f2s.com wrote:
> I have a problem. I'm writing a simulation program with a number of
> mechanical components represented as objects. When I create instances
> of objects, I need to reference (link) each object to the objects
> upstream and downstream of it, i.e.
>
> supply = supply()
> compressor = compressor(downstream=combustor, upstream=supply)
> combuster = combuster(downstream=turbine, upstream=compressor)
> etc.
>
> the problem with this is that I reference 'combustor' before is it
> created. If I swap the 2nd and 3rd lines I get the same problem
> (compressor is referenced before creation).
>
>
> aargh!!! any ideas on getting around this?
>
> Dave

I have done similar things in the past.  One useful trick is to define
a special class for connections, create a single instance of this
class, and make all your connections as attributes of this instance.
For example:

world = Simulation()

world.supply = Supply()
world.compressor = Compressor(downstream=world.cumbustor,
upstream=world.supply)
world.cumbuster = Combuster(downstream=world.turbine,
upstream=world.compressor)

Because Python lets you control attribute access to your simulation
world object, it is relatively easy to make proxy objects for
attributes which don't yet exist via __getattr__, and then to insert
the real object into the proxy via __setattr__.

Alternatively, the script (using the same syntax as shown above!) can
simply collect all the connection information when it is run, then make
a "real" structure later.  This works best if your simulation objects
(Supply, Compressor, Cumbuster) allow setting of the connection
attributes after instantiation.

Regards,
Pat




More information about the Python-list mailing list