Reflection: Calling Methods Dynamically by Name

Prateep Siamwalla teep at inet.co.th
Thu Jan 11 01:41:34 EST 2001


Chad,

You will want to use getattr() and apply()

Try this on the interpreter (apologies if the tabs/spaces don't come out
right):
---------------------------------------------------------------
>>> class MyClass:
...  def FunctionA(self):
...   print 'I am functionA'
...  def FunctionB(self):
...   print 'I am functionB'
...  def FunctionC(self,param1,param2):
...   print 'I am functionC'
...   print 'param1: ',param1
...   print 'param2: ',param2
...
>>>
>>> a = MyClass()
>>> function = getattr(a,'Function'+'A')
>>> function()
I am functionA
>>> function2 = getattr(a,'Function'+'B')
>>> function2()
I am functionB
>>> function3 = getattr(a,'Function'+'C')
>>> apply(function3,('this is param1','this is param2'))
I am functionC
param1: this is param1
param2: this is param2
---------------------------------------------------------

Hope this helps.
teep


<harrc at my-deja.com> wrote in message news:93jfur$9rj$1 at nnrp1.deja.com...
> Question for Guido or language experts:
>
> Does Python have the ability to call methods of a class by name?  For
> example, I have a string: "ProcessData" and the class MyClass has a
> method called ProcessData.  Is there a way I can do something like this:
>
> mc = MyClass()
> str = "ProcessData"
> args = ("Data", 1, 3)
> CallMethodByName(mc, str, args)
>
> or perhaps:
>
> mc = MyClass()
> str = "ProcessData"
> args = ("Data", 1, 3)
> mc.CallMethodByName(str, args)
>
>
> This reflection-esque behavior would be very useful.  Any ideas?
>
> Thanks,
>
> Chad Harrington
>
>
>
> Sent via Deja.com
> http://www.deja.com/





More information about the Python-list mailing list