using names before they're defined
Paddy
paddy3118 at netscape.net
Wed Jul 19 16:57:42 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
Hi Dave,
In Digital electronics we have what are called netlists, (and also
component lists)
We have component types (map them to component objects); named
instances of components (instances); then we have net types (you could
probably get away with one net type) which models connections between
ports on a component.
class Port:
def __init__(self, direction):
self.direction = direction
class Comp:
def __init__(self,compType,name):
self.upstream = Port("U")
self.downstream = Port("D")
self.name = name
self.compType = compType
class Link:
def __init__(self, name, *connections):
self.connections = connections
self.name = name
# Instantiate your components
supply1 = Comp("supply", "supply1")
supply2 = Comp("supply", "supply2")
compressor1 = Comp("compressor", "compressor1")
# Instantiate Links and link in ports of component intances
supply2comp = Link("supply2comp", supply1.downstream,
compressor1.upstream)
# ...
With a bit more effort you can create component and link factories
that will name instances with the variable they are assigned to
without having to put that information in twice.
- Paddy.
More information about the Python-list
mailing list