Calling a function dynamically
Eric Brunel
eric.brunel at N0SP4M.com
Thu Jan 8 11:01:22 EST 2004
Paradox wrote:
> 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
> #instance.run(*args)
>
> #This didn't work cause there was no __call__ attribute. Why?
> value = instance.__call__[functionName](*args)
The "function" is in fact a method on the instance, that is handled like a
regular attribute. So using getattr should do what you want:
value = getattr(instance, functionName)(*args)
__call__ is for a completely different purpose, which is to define instances
that behave like functions:
>>> class Spammer:
... def __call__(self):
... print 'spam'
...
>>> o = Spammer()
>>> o()
spam
HTH
--
- Eric Brunel <eric dot brunel at pragmadev dot com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list
mailing list