help in understanding the stackless code

MRAB python at mrabarnett.plus.com
Thu Jun 18 08:14:46 EDT 2015


On 2015-06-18 08:41, ravi wrote:
> hi,
> I am new to python and need to know why the calling of switch(1) invokes the function "listen" twice in the below program?
>
>
>
> import stackless
>
> class EventHandler:
>      def __init__(self,*outputs):
>          if outputs==None:
>              self.outputs=[]
>          else:
>              self.outputs=list(outputs)
>
>          self.channel = stackless.channel()
>          stackless.tasklet(self.listen)()
>
>      def listen(self):
>          print "in listen()..."
>          while 1:
>              val = self.channel.receive()
>              self.processMessage(val)
>              for output in self.outputs:
>                  self.notify(output)
>
>      def processMessage(self,val):
>          pass
>
>      def notify(self,output):
>          pass
>
>      def registerOutput(self,output):
>          print "in registerOutput()..."
>          self.outputs.append(output)
>
>      def __call__(self,val):
>          print "in __call__ ..."
>          self.channel.send(val)
>
> class Switch(EventHandler):
>      def __init__(self,initialState=0,*outputs):
>          EventHandler.__init__(self,*outputs)
>          self.state = initialState
>
>      def processMessage(self,val):
>          print "in processMessage() of Switch..."
>          self.state = val
>
>      def notify(self,output):
>          print "in notify() of switch..."
>          output((self,self.state))
>
> class Reporter(EventHandler):
>      def __init__(self,msg="%(sender)s send message %(value)s"):
>          EventHandler.__init__(self)
>          self.msg = msg
>
>      def processMessage(self,msg):
>          print "in processMessage() of Reporter..."
>          sender,value=msg
>          print self.msg % {'sender':sender,'value':value}
>
>
> if __name__ == "__main__":
>      reporter = Reporter()
>      switch = Switch(0,reporter)
>      switch(1)
>
>
>
>
> output:
> =========
>
> in __call__ ...
> in listen()...
> in listen()...
> in processMessage() of Switch...
> in notify() of switch...
> in __call__ ...
> in processMessage() of Reporter...
> <__main__.Switch instance at 0x8d822cc> send message 1
>
Is it because EventHandler has 2 subclasses, namely Switch and
Reporter, and you have an instance of each?




More information about the Python-list mailing list