[Tutor] Calling instance method using a string

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Nov 9 18:13:00 CET 2006


>> Say I have class A:
>>
>> class A:
>>     def myMethod( self ):
>>         print 'foo'
>>
>> a = A()
>
> getattr(a, 'myMethod')()
>
> The getattr() call gets the bound method, the extra parentheses at the 
> end call it.


Hi Bernard,

You can also do this in a controlled manner by treating the methods as 
functions, and using a dispatch table.  Concretely:

#########################################################
class TestDispatch:
     def add(self, x, y):
         return x + y

     def sub(self, x, y):
         return x - y

     def dontcallme(self):
         return "oh no"

     def dispatch(self, msg, *args):
         table = {"add" : self.add,
                  "sub" : self.sub}
         if msg in table:
             return table[msg](*args)
         print "Unrecognized message:", msg
         return None

def test():
     calc = TestDispatch()
     msg = None
     while msg != 'quit':
         msg = raw_input('cmd? ')
         print calc.dispatch(msg, 3, 4)
#########################################################

Try running test(), and then enter either "add" or "sub" at the prompt.

This approach differs from getattr() because we can prevent clients from 
calling dontcallme() by excluding it from our dispatch table, so it's more 
controlled.  Also, it's a techinque that's pretty programming-language 
agnostic.  However, it is a little more verbose than the equivalent 
getattr()-driven code.


More information about the Tutor mailing list