factory t at
Fri Nov 19 11:02:51 CET 2004

  Anyone want to comment on what they think of this following bit of a 
simple event framework?
  Are there any really obvious things I should be doing with this code 
that stop me from getting bitten on the arse in the future?

class Talker:
    def __init__( self ):
        self.listeners= []
    def AddListener( self, event, listener ):
        self.listeners.append( [ event, listener ] )

    def RemoveListener( self, event, listener ):
        for i, ( e,l ) in enumerate( self.listeners ):
            if (e == event ) and ( l==listener ):
                self.listeners.pop( i )
    def Talk( self, event, *args ):
        for i in self.listeners:
            evt, listener= i
            if evt == event:
                listener( *args )

class Listener:
    def HeardSomething( self, message ):
        print 'Listener.HeardSomething'
        print message

class FoobarTalker( Talker ):
    importantEvent= 42
    def SomethingHappened( self, something ):
        self.Talk( FoobarTalker.importantEvent, something )
l= Listener()
t= FoobarTalker()

t.AddListener( FoobarTalker.importantEvent, l.HeardSomething )
t.SomethingHappened( 'something' )
t.RemoveListener( FoobarTalker.importantEvent, l.HeardSomething )


More information about the Python-list mailing list