Is this..... evil?

Joshua Muskovitz joshm at taconic.net
Sat Feb 9 15:55:09 EST 2002


My suggestion would be for each type of receiver to simply create its own
dict which maps message types (strings) to local functions.  If it's in the
dict, then you can assume its callable, and thus avoid the logic per
incoming message.  If you set up your constructors correctly, you could even
inherit the list of existing handlers from the base classes.  Thus class
BaseReceiver could create the dict which handles the MsgA and MsgB types.  A
derived class could add a MsgC handler to the dict, etc.  This also allows
derived classes to "overload" base handlers by simply replacing the function
reference in the dict.

something like (coded off the top of my head, if it don't run, sorry :-)

class Receiver:
    def __init__(self):
        self.msgFuncs = {}

    def message(self, msg):
        if self.msgFuncs.has_key(msg.type):
            self.msgFuncs[msg.type](msg)

class F(Receiver):
    def __init__(self):
        Receiver.__init__(self)
        self.msgFuncs['fighto'] = rec_fighto

    def rec_fighto(self, msg):
        ...

class S(Receiver):
    def __init(self):
        Receiver.__init__(self)
        self.msgFuncs['spello'] = rec_spello
        self.msgFuncs['fighto'] = rec_fighto
        self.msgFuncs['none'] = rec_none

    ...

There are better ways to handle the dict adds, of course, but you get the
idea.  The cool thing about this is that on a per receiver basis you can
have different classes of messages still handled by a single common handler
(just point them to the same internal function).

--
# Joshua Muskovitz
# joshm at taconic.net
def lyyrs(sig): return '-'.join(sig.split()+["ly y'rs"])
lyyrs('Hire me!  I need the work!')




-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----



More information about the Python-list mailing list