Move dictionary from instance to class level

Frank Millman frank at chagford.com
Wed Aug 26 11:22:21 CEST 2009


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.

Frank






More information about the Python-list mailing list