Calling a function dynamically
tim.golden at viacom-outdoor.co.uk
Thu Jan 8 16:43:50 CET 2004
>From: JoeyTaj at netzero.com [mailto:JoeyTaj at netzero.com]
>Sent: 08 January 2004 15:42
>To: python-list at python.org
>Subject: Calling a function dynamically
>I would like to call a function whose name I supply at runtime.
>Something like this but it didn't work
>functionName = 'run'
>instance = ClassDef()
>args = [1, 2]
>#want the dynamic equivalant of
>#This didn't work cause there was no __call__ attribute. Why?
>value = instance.__call__[functionName](*args)
The __call__ method of an instance only exists if defined
for its class by the developer, typically so that instances
of the class can behave as though they were functions.
If you're really set on doing what you describe, make
use of the getattr function. Something like this should work:
>>> class c:
... def f (self, x, y): return x + y
>>> i = c ()
>>> print getattr (i, "f") (1, 2)
However, perhaps you don't really want to do it this way. A
common approach to this in Python is to use a dictionary
of functions. Doubtless there are others. If you could paint
a wider picture of what you're about, we could probably be
of more help.
This e-mail has been scanned for all viruses by Star Internet. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
More information about the Python-list