Move dictionary from instance to class level

Frank Millman frank at chagford.com
Wed Aug 26 04:22:41 EDT 2009


Hi all

I have a class that uses a dictionary to map message numbers to methods.

Here is a simple example -

    class MyClass(object):
        def __init__(self):
            self.method_dict = {}
            self.method_dict[0] = self.method_0
            self.method_dict[1] = self.method_1

        def on_message_received(self, msg):
            self.method_dict[msg]()

        def method_0(self):
            print 'in method_0'

        def method_1(self):
            print 'in method_1'

I have quite a few methods, so the dictionary is growing - up to 28 methods 
so far. To avoid
having to recreate the dictionary every time I create an instance of the 
class, I tried to move it
up to the class level. Unfortunately it does not work. This is what I 
tried -

    class MyClass(object):
        method_dict = {}
        method_dict[0] = method_0  # this gives an error
        method_dict[1] = method_1

        def on_message_received(self, msg):
            self.method_dict[msg]()

        def method_0(self):
            print 'in method_0'

        def method_1(self):
            print 'in method_1'

As written above, I get the following error -
    NameError: name 'method_0' is not defined

If I try self.method_0, I get 'self' is not defined.

If I try __class__.method_0, I get '__class__' is not defined.

If I try MyClass.method_0, I get 'MyClass' is not defined.

Is there any variation on this theme that will work?

#----------------------------------------------------

Ok, I found a variation that seems to work.

Is this the preferred way, or is there a better alternative?

    class MyClass(object):

        def on_message_received(self, msg):
            #self.method_dict[msg]()  # had to change this to get it to work
            self.method_dict[msg](self)

        def method_0(self):
            print 'in method_0'

        def method_1(self):
            print 'in method_1'

    MyClass.method_dict = {}
    MyClass.method_dict[0] = MyClass.method_0
    MyClass.method_dict[1] = MyClass.method_1

As you can see, I had to add 'self' to the method arguments when calling the 
method.

Any comments?

Thanks

Frank Millman





More information about the Python-list mailing list