Is this..... evil?

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Sat Feb 9 21:41:41 EST 2002


On 9 Feb 2002 18:21:31 GMT, Philip Swartzleonard <starx at pacbell.net> wrote:
>So i've been poking around with ways of doing this messaging thing, and 
>i think up this (sorry for the inanity of some of the names, i was sick 
>and tired when i worte this :):    	
>
>
>class Message:
>    type = "none"
>class FightoMessage(Message):
>    type = "fighto"
>class SpelloMessage(Message):
>    type = "spello"
>
>class Reciever:
>    def message( self, message ):
>        methname = 'rec_' + message.type
>        if hasattr(self, methname):
>            if callable(getattr(self, methname)):
>                getattr(self, methname)(message)

I recommend leaving the 'type' attributes out.

class Message: pass
class Fighto(Message): pass
class Spello(Message): pass

class Receiver: # i before e except after c!
    def message(self, msg):
        msgname = 'rec_' + msg.__class__.__name__
        if hasattr(self, msgno):
            # recommend leaving out the callable(), why let people define
            # non callable rec_ attrs?
            getattr(self, msgname)(message)

To the other poster who had the idea of using dicts to alias messages, you
can do the same with:

class F(Receiver):
    def rec_fighto(self, message):
        print "FIGHTO!!"
    rec_hacko = rec_fighto

>I dont think a better solution i could ever have seen. It does all the 
>work of a big ugly switch statment, with none of the uglyness OR the 
>hard-codedness. I can define new message types at will and only update 
>things that i WANT to recieve them.

Yes, you shouldn't be reinventing a type system with messages and receivers,
since the language already implements a perfectly good type systom with
messages and receivers (switching to smalltalk-speak since you're using it, but
the usual python terms are methods/attributes and objects).

>Also, is there any real reason to have the message classes inherit when 
>the only thing that seems to identify them is an attribute?

No, unless you wanted messages to have some messages of their own, which I
assume you did since otherwise you could have made them strings.  If you
do want all Messages to respond to a few common messages (small 'm'), like
'sender' or 'time_sent', then inheritance is natural.



More information about the Python-list mailing list