Newbie: calling the originating class ...

Diez B. Roggisch deets at nospam.web.de
Tue Aug 15 06:18:48 EDT 2006


donkeyboy wrote:

> This is probably very straightforwards to someone with experience, but
> I will try to explain my predicament:
> 
> I'm trying to code a simulation, where you have a Simulation class that
> knows everything about the simulation, and in turn classes that the
> Simulation calls when it wants to make new instances -- for the time
> being, let's call the called classes Agents (sorry, saw the Matrix
> again last night!).
> 
> In the Simulation class, there's information about the simulation that
> each Agent wants to know. As such, I wrote a method in the Simulation
> class for the Agents to call, to get the said required information.
> However, I can't figure out a way for the Agents to call the
> Simulations methods -- is this even possible?
> 
> The pseudo-code I'm using is as follows:
> 
> s = Simulation()
> 
> class Simulation:
>     # create a number of agents
>     ...
>     # Simulation information
>     important_stuff = 10
> 
>     def showImportant(self):
>     return important_stuff
> 
> class Agents:
>     my_stuff = s.showImportant
> 
> ... which fails: I get errors saying the global name 's' is not
> defined. Any thoughts? Is what I'm trying to do even possible, or
> should I be doing something else?

Besides the fact that the above can't work, as you can't instantiate a
Simulation object before defining its class, you have basically two options
here (while they come in many disguises):

 - have only one instance of Simulation and a defined way to access it - in
OO-terms called a singleton. There are several ways to accomplish that:

   - a "real" singleton or borg-pattern, that allows you to use the
Simulation constructor

   - a module global variable you assign it to & then use it.

   - classmethods

 - pass an instance of a Simulation to each Agent, either at
construction-time or later on explicit.


Depending on how the overall system is supposed to run, either ways have
their benefits - if you only run one simulation, the first approach enables
you to only use the simulation object where you need it, and not pass it
around to other objects that maybe don't need it themselves but have other
objects contained/instantiated that do so. But naturally, no parallel
universe with only one simulation....

Diez



More information about the Python-list mailing list