Method call from string

Peter Hansen peter at engcorp.com
Fri Jun 7 08:07:45 CEST 2002


ZnU wrote:
> 
> Say I've got a variable with the value 'do_something', and I have an an
> object that happens to have a do_something method. How can I call that
> method based on the value of the variable? Preferably without using
> eval() or similar.

>>> var = 'do_something'
>>> class A:
...   def do_something(self):
...      print 'ooga booga'
...
>>> a = A()
>>> getattr(a, var)
<bound method A.do_something of <__main__.A instance at 0x007B0110>>
>>> f = getattr(a, var)
>>> f()
ooga booga


-Peter



More information about the Python-list mailing list