开发者

Callback, observers, and asynch sockets in Python

I'm still a neophyte Python programmer and I'm trying to do something that is a bit over my head.

What I've done is create a simple IRC bot using asyncore (and asynchronous sockets module). The client runs in a continuous loop, listening to the conversation in the channel. What I would like to do (I think?) is implement an observer pattern so I can respond to events. I imagine it would look somthing like this:

class MyBot(object):

   def __init__(self):
      bot = MyIRCClient(server='whatever', channel='#whatever')
      bot.observe(event='join', handler='log_join')
      b开发者_如何学运维ot.connect() # Bot is now listening continously in a loop

   def log_join(self, e):
      print e + ' joined the channel.'

I'm basing this design around what I know of observers used in the various Javascript frameworks. I don't know if the same technique can or should be applied here. Any suggestions?


While Observer is not a particularly popular DP (design pattern) in Python, it's not a totally "alien" one either, so if you're familiar with it, go right ahead. However, the normal way to call observe would be with handler=self.log_join, a callback that's actually a callable, not with a string value forcing the bot to perform introspection to find out what it actually has to call when the event occurs (and not even giving it a self to refer to the object it's supposed to perform introspection on -- shudder!).

Callback is a perfectly reasonable and popular DP in Python, but that's because passing around first-class callables (functions, bound methods, classes, instances of classes with a __call__ method, etc, etc) is so wonderfully easy (pretty trivial, actually;-).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜