Move dictionary from instance to class level

MRAB python at mrabarnett.plus.com
Wed Aug 26 08:40:56 EDT 2009


Frank Millman wrote:
> On Aug 26, 10:54 am, Chris Rebert <c... at rebertia.com> wrote:
>> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman<fr... at chagford.com> wrote:
>>
>> A
>>
>> class MyClass(object):
>>     def on_message_received(self, msg):
>>         self.method_dict[msg](self)
>>
>>     def method_0(self):
>>         print 'in method_0'
>>
>>     def method_1(self):
>>         print 'in method_1'
>>         method_dict
>>
>>     method_dict = {0: method_0, 1: method_1}
>>     #note this comes *after* the methods in question have been defined
>>
> 
> Thanks, Chris. This is much better.
> 
>> Is there some reason you aren't using a list instead of a dict?
>> e.g. method_dict = [method_0, method_1, method_2, etc]
>>
>> For that matter, why are you associating methods with integers in the
>> first place?
>>
> 
> I actually use constants to define my messages, like this -
> 
> (MESSAGE_ONE
> ,MESSAGE_TWO
> ,MESSAGE_THREE
> ) = xrange(3)
> 
> I can then refer to the messages by their description, but internally it 
> uses integers.
> 
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
 >>>



More information about the Python-list mailing list