Private class?

Jack Diederich jack at performancedrivers.com
Thu Apr 21 11:33:00 EDT 2005


On Thu, Apr 21, 2005 at 06:13:02AM -0700, codecraig wrote:
> Hi,
>   First, I come from a Java background.
> 
>   Ok, so I have this idea that I want to create an EventBus...basically
> a central class where objects can register themselves as listeners for
> different events.  This central class also has methods so that objects
> can fire events.  Something like this...
> 
> Say we have object MrTree and object MotherNature.  MrTree listens for
> EVENT_GROW_LEAVES.  So, when MrTree "hears" about EVENT_GROW_LEAVES,
> MrTree will do just that, grow some leaves.  So, while our python app
> is running, MotherNature needs to tell MrTree to grow leaves.  I am
> suggesting something like this...
> 
> 1. MrTree has a method, growLeaves()
> 
> 2. MrTree registers for the event, EventBus.register(MrTree,
> EVENT_GROW_LEAVES)
> 
> 3. MotherNature fires grow leaves, EventBus.fire(EVENT_GROW_LEAVES)
> 
> 4. MrTree's growLeaves method gets called by EventBus.
> 
<snip>

Singletons are overrated, if you need a namespace just use a class or
module as another responder suggested.  Some of the indirection you
need to do this in Java goes away in python because you can do things
like pass around bound function objects.  Here is some code that includes
those  suggestions.

class EventCaller(object):
  def __init__(self):
    self.listeners = []
    return
  def append(self, listener):
    self.listeners.append(listener)
    return
  def __call__(self):
    for (listener) in self.listeners:
      listener()
    return

class EventBus(object):
  growLeaves = EventCaller()

class MrTree(object):
  def __init__(self):
    EventBus.growLeaves.append(self.growLeaves)

  def growLeaves(self): pass

class MotherNature(object):
  def doStuff(self):
    EventBus.growLeaves()


The EventCaller class is overloaded to behave both like a list and
like a function.  The EventBus class never gets instantiated, it is
just used as a place to lookup the different event queues.  MrTree
doesn't need to inherit from an interface class, his growLeaves method
is just a function that we can pass around.

-jackdied



More information about the Python-list mailing list