Reflection: Calling Methods Dynamically by Name

Mike Fletcher mfletch at tpresence.com
Thu Jan 11 01:03:54 EST 2001


method = getattr( objectInstance, someString )
method( "Data", 1, 3)

or

apply( method, arguments )

Note that str is a builtin function for converting objects to strings, so
it's not generally used as a variable in Python.

HTH,
Mike

-----Original Message-----
From: harrc at my-deja.com
To: python-list at python.org
Sent: 1/11/2001 12:22 AM
Subject: Reflection: Calling Methods Dynamically by Name

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/
-- 
http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list