Newbie: calling the originating class ...

Steve Holden steve at holdenweb.com
Tue Aug 15 06:15:20 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?
> 
Well obviously your agents each need a reference to the simulation. In 
the simulation methods the simulation instance can be referred to as 
self, so you can pass that as an argument to the agent creator. As in:

sholden at bigboy ~/Projects/Python
$ !cat
cat test44.py
#
# Calling all reactive agents (with apologies to William Burroughs)
#
class Simulation:

     def __init__(self, howmany):
         self.agents = []
         for i in range(howmany):
             self.agents.append(Agent(self, i))

     def showImportant(self, agent):
         return agent.number, self

     def listAgents(self):
         for a in self.agents:
             a.showMe()

class Agent:

     def __init__(self, sim, number):
         self.sim = sim
         self.number = number

     def showMe(self):
         print "Agent", self.number, "reporting:"
         result = self.sim.showImportant(self)
         print result

s = Simulation(5)
s.listAgents()

sholden at bigboy ~/Projects/Python
$ python test44.py
Agent 0 reporting:
(0, <__main__.Simulation instance at 0x186c6c8c>)
Agent 1 reporting:
(1, <__main__.Simulation instance at 0x186c6c8c>)
Agent 2 reporting:
(2, <__main__.Simulation instance at 0x186c6c8c>)
Agent 3 reporting:
(3, <__main__.Simulation instance at 0x186c6c8c>)
Agent 4 reporting:
(4, <__main__.Simulation instance at 0x186c6c8c>)

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list