Reflection: Calling Methods Dynamically by Name

Alex Martelli aleaxit at yahoo.com
Thu Jan 11 04:39:06 EST 2001


<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

Yes, as I've seen other answers have already showed you.  (You actually
seem to want to call the method on an _instance_ of the class, of course).

> 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)

One way to let you use the exact syntax you desire:

def CallMethodByName(instance, method_name, method_args):
    method_object = getattr(instance, method_name)
    return method_object(*method_args)

The getattr will raise an attribute-error exception if
the instance does NOT have some attribute named with
the string method_name refers to; if the attribute IS
there, but is not callable, you'll get a type-error from
the following line instead.  If these are not the exact
exceptions you desire to receive for such usage errors,
you will add try/except blocks to translate them to
whatever different exceptions you require (but, DO use
exceptions to signify such errors -- it's by far most
often the best approach).

The '*method_args' syntax takes a tuple, referred to by
method_args, and applies it as arguments to the call
being performed (new in Python 2.0: the apply built-in
function, which I see has been also suggested, is how
you would do that in older Python versions -- it also
keeps working in 2.0, of course).


Alex






More information about the Python-list mailing list