Move dictionary from instance to class level

Frank Millman frank at chagford.com
Wed Aug 26 10:54:32 EDT 2009


"MRAB" <python at mrabarnett.plus.com> wrote in message 
news:mailman.444.1251290454.2854.python-list at python.org...
> An alternative is:
>
> >>> class MyClass(object):
> ...     def on_message_received(self, msg):
> ...         try:
> ...             getattr(self, "method_%d" % msg)()
> ...         except AttributeError:
> ...             raise Exception("Unknown message")
> ...     def method_0(self):
> ...         print 'in method_0'
> ...     def method_1(self):
> ...         print 'in method_1'
> ...
> >>> my_obj = MyClass()
> >>> my_obj.on_message_received(0)
> in method_0
> >>> my_obj.on_message_received(1)
> in method_1
> >>> my_obj.on_message_received(2)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 6, in on_message_received
> Exception: Unknown message

I like the idea. Unfortunately my real-world situation is a little more 
complex than my simple example implied.

This is a more typical example -

    (EVT_GETLOGIN
    ,EVT_LOGOUT
    ,EVT_GETMENUOPT
    ,EVT_GOTFOCUS
    ,EVT_LOSTFOCUS
    ,EVT_BUTTONCLICKED
    ,EVT_CHECKBOX
    ...
    ) = xrange(28)

    method_dict = {}
    method_dict[EVT_GETLOGIN] = onGetLogin
    method_dict[EVT_LOGOUT] = onLogout
    method_dict[EVT_GETMENUOPT] = onGetMenuOpt
    method_dict[EVT_GOTFOCUS] = onGotFocus
    method_dict[EVT_LOSTFOCUS] = onLostFocus
    method_dict[EVT_BUTTONCLICKED] = onButtonClicked
    method_dict[EVT_CHECKBOX] = onCheckBox

You can probably figure out from my method names what I am doing here - the 
messages are sent by a thin client (wxPython), and processed by a server.I 
am anticipating some "don't do that" responses, but I like the concept, and 
so far it is very fast and responsive, so I will pursue it for now.

Thanks for the input.

Frank





More information about the Python-list mailing list