On Thu, Aug 19, 2010 at 4:27 PM, Tim Daneliuk <tun...@tundraware.com> wrote: > Problem: > > Given tuples in the form (key, string), use 'key' to determine > what string method to apply to the string: > > key operation > ----------------------- > > l lower() > u upper() > t title() > ... > > Commentary: > > Easy, right? Well ... except that I would really, really like > to avoid cascading ifs or eval based solutions. I'd like to implement > this as a jump table dictionary: > > jt = { 'l' : lower_function reference, > 'u' : upper_function reference, > ... > } > > So I could then do this: > > string = jt[key](string) > > But There's A Problem: > > I tried to do this: > > jt = {'l', "".lower, > 'u', "".upper, > ... > } > > You can get away with this because all string objects appear to point to > common > method objects. That is,: id("a".lower) == id("b".lower) > > HOWEVER, you cannot then do this: > > string = jt[key](string) > > Why? Because the methods of a string, while common to all strings > *do not accept an arg*. They are implemented to "know" about the > string instance they "belong to" (that contains them).
Right; by looking the method up on an instance you get a "bound" method that is "bound" to the instance you got it from and already has self filled-in. > (Forgive me here, I am probably not using some of the OO arcana properly...) > <snip> > > How do you get a reference to a method found in one object instance, but > actually apply it to another instance of the same class? I'm guessing this > may > involve fiddling with some of the internal __ variables, but I'm not > quite sure where to go next. You must access the method from the class rather than the instance; this produces an "unbound" method that is not bound to a specific instance and does not have self already filled-in. In your dictionary, replace "".lower with str.lower, and so on for the other methods. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list