On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman<fr...@chagford.com> wrote: > 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.
Right, because you're in the *class* body; there's no "current instance" to be "self"; in fact, there's not even any class for there to be instances of yet. > If I try __class__.method_0, I get '__class__' is not defined. Right, because the class isn't created until its body has finished executing > If I try MyClass.method_0, I get 'MyClass' is not defined. See previous note. The class name can't be bound to anything until the class itself has been created. > 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? 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 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? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list