Calling a function dynamically
eric.brunel at N0SP4M.com
Thu Jan 8 17:01:22 CET 2004
> 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 "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()
- 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