Re: [Tutor] Calling instance method using a string

2006-11-09 Thread Danny Yoo
 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.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling instance method using a string

2006-11-09 Thread Bernard Lebel
Thanks everyone for the advice.


Bernard



On 11/9/06, Danny Yoo [EMAIL PROTECTED] wrote:
  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.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor